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
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
分析:提示类似于中序遍历,每个节点的right指向它的按中序遍历的顺序的节点。这里向处理左子树,将root->right指向中序遍历后的根节点,再将左子树的最右的节点指向原来的右节点。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
//获取一个树的最下方的右节点,这也是中序遍历的尾节点
TreeNode* tail(TreeNode* root)
{
if(!root->right)
return root;
else return tail(root->right);
}
public:
void flatten(TreeNode* root) {
TreeNode* left,*right;
if(!root)
return;
left=root->left;
right=root->right;
if(left)
{
flatten(left);
TreeNode* ltail=tail(left);
root->right=left;
root->left=NULL;
flatten(right);
ltail->right=right;
ltail->left=NULL;
}else
flatten(right);
return;
}
};