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.
/**
* 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 {
public:
void flatten(TreeNode* root) {
if (root == NULL)
return;
TreeNode* rightNode = root->right;//保存右孩子
TreeNode* tmp = root->left;
while (tmp && tmp->right)
{
tmp = tmp->right;
}//找到右子的直接前驱
if (tmp)//如果左孩子不为空
{
tmp->right = rightNode;//让直接前驱指向保存的右孩子
root->right = root->left;//右指针指向左孩子
root->left = NULL;//左指针指向空
flatten(root->right);//对左孩子作同样的处理
}
flatten(rightNode);//对右孩子作同样的处理
}
};