Skip to content

Commit da824b5

Browse files
author
applewjg
committed
Update
1 parent 949555c commit da824b5

File tree

1 file changed

+46
-4
lines changed

1 file changed

+46
-4
lines changed

FlattenBinaryTreetoLinkedList.h

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/*
2-
Author: Annie Kim, [email protected]
2+
Author: Annie Kim, [email protected] : King, [email protected]
33
Date: Apr 28, 2013
4-
Update: Sep 29, 2013
4+
Update: Oct 7, 2014
55
Problem: Flatten Binary Tree to Linked List
66
Difficulty: Medium
77
Source: http://leetcode.com/onlinejudge#question_114
@@ -27,7 +27,7 @@
2727
\
2828
6
2929
Hints:
30-
If you notice carefully in the flattened tree, each node's right child points to the next node
30+
If you notice carefully in the flattened tree, each node's right child points to the next node
3131
of a pre-order traversal.
3232
3333
Solution: Recursion. Return the last element of the flattened sub-tree.
@@ -45,10 +45,52 @@
4545
class Solution {
4646
public:
4747
void flatten(TreeNode *root) {
48+
flatten_3(root);
49+
}
50+
51+
void flatten_1(TreeNode *root) {
52+
if (root == NULL) return;
53+
flatten_1(root->left);
54+
flatten_2(root->right);
55+
if (root->left == NULL) return;
56+
TreeNode *p = root->left;
57+
while (p->right) p = p->right;
58+
p->right = root->right;
59+
root->right = root->left;
60+
root->left = NULL;
61+
}
62+
63+
TreeNode * dfs (TreeNode * root, TreeNode * tail){
64+
if(root == NULL) return tail;
65+
root->right = dfs(root->left,dfs(root->right,tail));
66+
root->left = NULL;
67+
return root;
68+
}
69+
void flatten_2(TreeNode *root) {
70+
if(root == NULL) return;
71+
dfs(root, NULL);
72+
}
73+
void flatten_3(TreeNode *root) {
74+
if(root==nullptr) return;
75+
stack<TreeNode*> s;
76+
s.push(root);
77+
while(!s.empty()){
78+
auto p=s.top();
79+
s.pop();
80+
if(p->right) s.push(p->right);
81+
if(p->left) s.push(p->left);
82+
p->left = nullptr;
83+
if(!s.empty()){
84+
p->right=s.top();
85+
}else p->right = nullptr;
86+
}
87+
}
88+
89+
void flatten_4(TreeNode *root) {
4890
TreeNode *end = NULL;
4991
flattenRe(root, end);
5092
}
51-
93+
5294
void flattenRe(TreeNode *node, TreeNode *&end) {
5395
if (!node) return;
5496
TreeNode *lend = NULL, *rend = NULL;

0 commit comments

Comments
 (0)