问题描述:
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
解题思路:
从题目看出,是将一棵二叉树按顺序掰直,全变为右子树。从根开始,左子树接到右子树,原来的右孩子接该左子树最右孩子的后面。如此递归。
class Solution {
public:
void flatten(TreeNode* root) {
if(root==NULL) return ;
if(root->left!=NULL)
{
TreeNode *cur=root->left;
while(cur->right!=NULL)
cur=cur->right;
cur->right=root->right;
root->right=root->left;
root->left=NULL;
}
flatten(root->right);
}
};