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
I finished this problem in a direct way. However, the result was Runtime Error because I didn't set the left child to null when I submitted the first time.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private :
vector<TreeNode *> temp ;// record the preOrder result
public:
void preOrder(TreeNode *root){
temp.push_back(root);
if(root->left) preOrder(root->left);
if(root->right) preOrder(root->right);
}
void flatten(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
temp.clear();
if(root == NULL) return ;
preOrder(root);
for(int i = 0; i< temp.size()-1; i++)
{
temp[i]->right = temp[i+1];
temp[i]->left = NULL ;//essential
}
}
};
There is another way to solve this problem. Initially, root-->left, root-->right,
if(root->left==null)
nothing needs to do.
if(root->left!=null){
find the rightest node of root->left
rightest node->next=root->right;
root->right=root->left; //because of the pre-order
}
The following is the code :
/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
TreeNode *p;
if(root==NULL) return;
flatten(root->left);
flatten(root->right);
if(root->left==NULL) return;
p=root->left;
while(p->right!=NULL) p=p->right;
p->right=root->right;
root->right=root->left;
root->left=NULL;
return;
}
};
Python Nonrecursive Version (Preorder, ref to https://blog.csdn.net/taoqick/article/details/82495508):
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def flatten(self, root):
stack = []
prev,cur = None,root
while (cur != None or stack):
while (cur != None):
if (cur.right != None):
stack.append(cur.right)
if (prev != None):
prev.left = None
prev.right = cur
prev = cur
cur = cur.left
if (stack):
cur = stack.pop()