[Leetcode] flatten binary tree to linked list

Source: Internet
Author: User

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

For example,
Given

         1        /        2   5      / \        3   4   6

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

Just put the elephant in the refrigerator for a few steps.

1. Flatten the left subtree. 2. insert it to the right subtree of the root node and the root node. 3. Repeat 1, 2.

The idea is not difficult, and the code is a bit confusing. The implementation of the details is: Make the left subtree of the root into the flatten (root. left), save the right subtree temp = root. right, let root. right = root. left, and then the left, Root. left = NULL.

Then go to the far end of the right side, while (root. Right! = NULL) root = root. Right and then root. Right = temp to continue processing.

The Code is as follows:

public void flatten(TreeNode root) {        if(root==null) return;        TreeNode p=root;        while(p!=null){            if(p.left==null){                p=p.right;            } else {                if(p.right==null) {                    TreeNode temp=p.left;                    p.left=null;                    p.right=temp;                    p=p.right;                } else {                                TreeNode tempRight=p.right;                TreeNode tempLeft=p.left;                p.right=null;                flatten(p.left);                p.left=null;                p.right=tempLeft;                while(p.right!=null){                    p=p.right;                }                p.right=tempRight;                }            }                    }            }


[Leetcode] 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.