Leetcode Flatten Binary Tree to Linked List

Source: Internet
Author: User


Flatten Binary Tree to Linked List

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

Click to show hints.


Having a deep understanding of pointer and Tree operations, this question is very simple, but not well understood, so it is very difficult.

Important: you cannot change the structure of a tree node that has not been accessed during traversal.

Because of this, this question cannot be written as a normal first-order traversal program.

After careful observation, we will find two features:

1. The modified tree only has the right subtree,

2. The structure of a accessed node can be modified.

Then we can use reverse first-order traversal-because we first access the rightmost right subtree, this right subtree will not be needed in subsequent access, you can change the tree structure.

After thinking about this, this question becomes very simple.

The following two procedures for reverse first-order traversal are very simple:

1.

Void flatten (TreeNode * root) {if (! Root) return; TreeNode * dummy = new TreeNode (-1); flatten (root, dummy); // root = dummy-> right; delete dummy ;} void flatten (TreeNode * root, TreeNode * (& res) {if (! Root) return; flatten (root-> right, res); flatten (root-> left, res); root-> right = res-> right; res-> right = root; root-> left = nullptr ;}

2.

void flatten2(TreeNode *root) {if (!root) return;flatten2(root->right);flatten2(root->left);if (root->left){TreeNode *rMost = root->left;while (rMost->right) rMost = rMost->right;rMost->right = root->right;root->right = root->left;root->left = nullptr;}}















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.