題目
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;
}
另外,我開通了微信公衆號--分享技術之美,我會不定期的分享一些我學習的東西.