Problem
Given a binary tree, 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
click to show hints.
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
Code
void flatten_r(TreeNode *root,TreeNode **last) { if(!root) return; if(*last){ (*last)->right = root; (*last)->left = 0; } TreeNode *l = root->left; TreeNode *r = root->right; *last = root; flatten_r(l,last); flatten_r(r,last); } void flatten(TreeNode *root) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. TreeNode *last = 0; flatten_r(root,&last); }
No comments:
Post a Comment