题目:
Given a binary tree, flatten it to a linked list in-place.
For example,
Given1 / 2 5 / 3 4 6The flattened tree should look like:
1 2 3 4 5 6
其实就是把二叉树按前序遍历顺序以右指针为next搞成一个单链表,想了半天前驱、后继貌似没折,后来想把左子树先平掉,再把左子树合到右子树顶端之上,再平掉原先右子树的那个结点为根的树即可。代码如下:
1 void flatten(TreeNode *root) { 2 if(root==NULL) return; 3 TreeNode* t,*right=root->right; 4 flatten(root->left);//平掉左子树 5 if(root->left){//把左子树插入到右子树与根之间 6 t = root->left; 7 while(t&&t->right) t=t->right; 8 right = t->right = root->right; 9 root->right=root->left; 10 root->left=NULL; 11 } 12 flatten(right);//平掉右子树 13 }