Flatten Binary Tree to Linked List
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
/**
* 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 flatten(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
// use a 'pre' pointer to track the predecessor of the current node
// use pre-order traversal
if (!root)
return;
stack
TreeNode *pre = NULL;
my_stack.push(root);
while (!my_stack.empty())
{
TreeNode *p = my_stack.top();
// visit p
if (pre)
{
pre->right = p;
pre->left = NULL;
}
pre = p;
// pop current node
my_stack.pop();
// push right and left children into stack
if (p->right) my_stack.push(p->right);
if (p->left) my_stack.push(p->left);
}
}
};
No comments:
Post a Comment