[Leetcode] [Java] Flatten Binary Tree to Linked List

Source: Internet
Author: User

Title:

Given a binary tree, flatten it to a linked list in-place.

For example,
Given

         1        /        2   5      /\        3   4   6

The flattened tree should look like:
   1         2             3                 4                     5                         6

Test Instructions:

Given a binary tree, it turns itself into a single-linked list.

For example, given

         1        /        2   5      /\        3   4   6
transformed into a flat tree as shown:

   1         2             3                 4                     5                         6

Algorithm Analysis:

* This method directly on root node, first temporarily save the left and right subtree, if Root has a left dial hand tree, the root.right attached to the root.left,root.left to null, and then on the left subtree of the tree

* Find rightmost node and put the right subtree before it on the rightmost.right.

* Once done, the left subtree of root has been grafted between the right subtree and root, and the original left subtree becomes null and can be root.right recursively.

AC Code:

<span style= "Font-family:microsoft yahei;font-size:12px;" >/** * Definition for Binary tree * public class TreeNode {*     int val, *     TreeNode left, *     TreeNode right;     TreeNode (int x) {val = x;} *} */public class Solution {public    void flatten (TreeNode root)     {        if (root = = null) return;        if (root.left! = null)        {            TreeNode left = root.left;            TreeNode right = Root.right;            Root.left = null;            Root.right = left;            TreeNode rightmost = root.right;            while (rightmost.right! = null)            {                rightmost = rightmost.right;            }            Rightmost.right = right;        }        Flatten (root.right);    }} </span>

Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source

[Leetcode][java] Flatten Binary Tree to Linked List

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.