难度3,出现频率3
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
思路: 用递归挺简单的--第一个一次通过bug free的代码,oh yeah!
void flatten(TreeNode *root) {
if(root == NULL) return;
flatten(root->left);
flatten(root->right);
TreeNode *temp = root->right;
root->right = root->left;
root->left = NULL;
TreeNode *cur = root;
while(cur->right != NULL){
cur = cur->right;
}
cur->right = temp;
}
No comments:
Post a Comment