题目
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
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
解题思路
本题的意思是将二叉树按照先序遍历的方式,串成一个链表。
代码实现
void flatten( TreeNode *root){
if (root == NULL) return;
flatten(root->left);
flatten(root->right);
if (root->left == NULL) return ;
TreeNode *pre = root->left;
wihle (pre->right != NULL)
pre = pre->right;
pre->right = root->right;
root->right = root->left;
root->left = NULL;
}
另外,我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.