Given a binary tree, flatten it to a linked list in-place.
For example,
Given
Given
1 / \ 2 5 / \ \ 3 4 6
1 \ 2 \ 3 \ 4 \ 5 \ 6
Hints:
Analysis:
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 binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void helper(TreeNode *root, TreeNode*& lastVisited) {
if (root == NULL)
return;
//preorder, the root->right will be overrided when calling helper(root->left, lastVisited)
//need to be saved
TreeNode* right = root->right;
if (lastVisited != NULL)
{
lastVisited->left = NULL;
lastVisited->right = root;
}
//remember last visited
lastVisited = root;
helper(root->left, lastVisited);
helper(right, lastVisited);
}
void flatten(TreeNode *root) {
TreeNode* lastVisited = NULL;
helper(root, lastVisited);
}
};
No comments:
Post a Comment