-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path649.binary-tree-upside-down.cpp
142 lines (131 loc) · 3.09 KB
/
649.binary-tree-upside-down.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
// Tag: Binary Tree, Depth First Search/DFS, Divide and Conquer
// Time: O(N)
// Space: O(H)
// Ref: Leetcode-156
// Note: -
// Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes.
// Return the new root.
//
// **Example1**
//
// ```plain
// Input: {1,2,3,4,5}
// Output: {4,5,2,#,#,3,1}
// Explanation:
// The input is
// 1
// / \
// 2 3
// / \
// 4 5
// and the output is
// 4
// / \
// 5 2
// / \
// 3 1
// ```
//
// **Example2**
//
// ```plain
// Input: {1,2,3,4}
// Output: {4,#,2,3,1}
// Explanation:
// The input is
// 1
// / \
// 2 3
// /
// 4
// and the output is
// 4
// \
// 2
// / \
// 3 1
// ```
//
//
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: the root of binary tree
* @return: new root
*/
TreeNode* upsideDownBinaryTree(TreeNode *root) {
// write your code here
if (!root || !root->left) {
return root;
}
TreeNode *new_root = upsideDownBinaryTree(root->left);
root->left->left = root->right;
root->left->right = root;
root->left = nullptr;
root->right = nullptr;
return new_root;
}
};
class Solution {
public:
/**
* @param root: the root of binary tree
* @return: new root
*/
TreeNode* upsideDownBinaryTree(TreeNode *root) {
// write your code here
stack<TreeNode *> st;
TreeNode * cur = root;
while (cur) {
st.push(cur);
cur = cur->left;
}
TreeNode *dummy = new TreeNode(0);
TreeNode *pre = dummy;
while (!st.empty()) {
TreeNode *cur = st.top();
st.pop();
pre->right = cur;
pre->left = cur->right;
pre = cur;
cur->left = nullptr;
cur->right = nullptr;
}
// fix dummy memory leak in real code
return dummy->right;
}
};
class Solution {
public:
/**
* @param root: the root of binary tree
* @return: new root
*/
TreeNode* upsideDownBinaryTree(TreeNode *root) {
TreeNode * pre = nullptr;
TreeNode *cur = root;
TreeNode *rchild = nullptr;
// like reverse single linked list with special right child
while(cur){
TreeNode *tmp = cur->left;
cur->left = rchild;
rchild = cur->right;
cur->right = pre;
pre = cur;
cur = tmp;
}
return pre;
}
};