Leetcode:flatten Binary Tree to Linked List

Source: Internet
Author: User

Requirements: Given A binary tree, flatten it to a linked list in-place. The tree that transforms the two fork into a flat sequence. Like what:

The idea of knot problem:

The question has a hint that the sequence of the transformed tree is exactly the sequence of the two-fork-tree pre-sequence traversal, so the first idea of the problem is to make use of the way of the pre-order traversal.

The second idea: we can use the idea of recursion, first to the root node processing, the root of the left subtree to the right subtree, in the left subtree in the right end of the node "grafted" to the right subtree, and then the above-obtained sub-tree. Next, the next node of the current binary tree is processed in the same way. Look at the following diagram to be clear.

I realized the second way of thinking, the code is as follows:

1 structTreeNode {2     intVal;3treenode*Left ;4treenode*Right ;5TreeNode (intx): Val (x), left (null), right (null) {}6 };7 8 voidFlatten (TreeNode *root)9 {Ten     if(NULL = =root) One         return; A     //using a non-recursive method of stack -TreeNode *left = root->Left ; -TreeNode *right = root->Right ; the  -     if(left) { -Root->right =Left ; -Root->left =NULL; +  -TreeNode *ptemp =Left ; +          while(ptemp->Right ) APtemp = ptemp->Right ; atPtemp->right =Right ; -  -Flatten (root->Right ); -     } -}

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.