Given a binary tree, flatten it to a linked list in-place.
For example,
Given
Given
1 / \ 2 5 / \ \ 3 4 6
1 \ 2 \ 3 \ 4 \ 5 \ 6Solution:
Using recursion, every time, link the right sub-tree to the deepest leaf node of the left sub-tree.
My code accepted in one pass, first time~!! Woo-Hoo~
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 a binary tree node. | |
* 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; | |
if(root->left!=NULL) | |
flatten(root->left); | |
if(root->right!=NULL) | |
flatten(root->right); | |
TreeNode* tmpRight=root->right; | |
TreeNode* leftLeef; | |
if(root->left==NULL) | |
leftLeef=root; | |
else{ | |
leftLeef=root->left; | |
while(leftLeef->right!=NULL){ | |
leftLeef=leftLeef->right; | |
} | |
} | |
if(root->left!=NULL) | |
root->right=root->left; | |
root->left=NULL; | |
leftLeef->right=tmpRight; | |
} | |
}; |
No comments:
Post a Comment