Leetcode (114) Flatten Binary tree to linked List

Source: Internet
Author: User

Topic analysis

Given a binary tree and 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

Hints:
If you are notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.


The analysis is as follows:

Because the result of the last flatten is the result of the tree's preceding sequence traversal, the flatten transformation is considered while the forward traversal is carried out.


The code is as follows:

48ms too large set/** * Definition for binary tree * struct TreeNode {* int val;
 * TreeNode *left;
 * TreeNode *right;
 * TreeNode (int x): Val (x), left (null), right (NULL) {} *};
        * * Class Solution {public:void flatten (TreeNode *root) {if (root==null) return;
        Stack<treenode*> Node_stack;
        Node_stack.push (root);
        treenode* New_root=null;
        treenode* Cur=null;
        treenode* Next=null;
            while (!node_stack.empty ()) {cur=node_stack.top ();
            Node_stack.pop ();
            if (cur->right!=null) Node_stack.push (cur->right);
            if (cur->left!=null) Node_stack.push (cur->left);
                if (new_root==null) {new_root=cur;
                Next=cur;
            cur->left=null;
                else {next->right=cur;
                next->left=null;
            Next=cur;
  }
        }      Root=new_root; }
};

Summary:

(1) logic is very important, in the while loop body, you should first put cur->right, cur->left pressure stack, and then to flatten. If the order is reversed, some nodes that have not yet been processed will be destroyed in the flatten, and the nodes will be pressed onto the stack, and then an error can occur.


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.