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.