Created
August 31, 2014 07:02
-
-
Save xiren-wang/9a6dec35c7676b7da5a7 to your computer and use it in GitHub Desktop.
Flatten Binary Tree to Linked List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for binary tree | |
* struct TreeNode { | |
* int val; | |
* TreeNode *left; | |
* TreeNode *right; | |
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}\ 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 | |
* }; | |
*/ | |
class Solution { | |
public: | |
void flatten(TreeNode *root) { | |
//root -> leftSon -> ... -> lastLeft -> right -> ... -> lastRight | |
if (!root) | |
return; | |
TreeNode *last=NULL; | |
root = flatten(root, last); | |
return ; | |
} | |
TreeNode *flatten(TreeNode *root, TreeNode *&last) { | |
TreeNode *left = root->left; root->left = NULL; | |
TreeNode *right = root->right; root->right = NULL; | |
TreeNode *lastLeft=NULL; | |
if (left) { | |
root->right = flatten (left, lastLeft); | |
} | |
TreeNode *lastRight=NULL; | |
if (right) { | |
if (lastLeft) | |
lastLeft->right = flatten (right, lastRight); | |
else | |
root->right = flatten(right, lastRight); | |
} | |
//update last | |
if (lastRight) | |
last = lastRight; | |
else if (lastLeft) | |
last = lastLeft; | |
else | |
last = root; | |
return root; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment