-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path649.binary-tree-upside-down.py
129 lines (115 loc) · 2.78 KB
/
649.binary-tree-upside-down.py
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
# 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
# ```
#
#
from lintcode import (
TreeNode,
)
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the root of binary tree
@return: new root
"""
def upside_down_binary_tree(self, root: TreeNode) -> TreeNode:
# write your code here
if root is None or root.left is None:
return root
new_root = self.upside_down_binary_tree(root.left)
root.left.left = root.right
root.left.right = root
root.right = None
root.left = None
return new_root
class Solution:
"""
@param root: the root of binary tree
@return: new root
"""
def upside_down_binary_tree(self, root: TreeNode) -> TreeNode:
# write your code here
stack = []
cur = root
while cur is not None:
stack.append(cur)
cur = cur.left
dummy = TreeNode(0)
pre = dummy
while len(stack) > 0:
cur = stack.pop()
pre.right = cur
pre.left = cur.right
pre = cur
cur.left = None
cur.right = None
return dummy.right
class Solution:
"""
@param root: the root of binary tree
@return: new root
"""
def upside_down_binary_tree(self, root: TreeNode) -> TreeNode:
# write your code here
pre = None
cur = root
rchild = None
# Similar to reversing a singly linked list with special right child handling
while cur:
tmp = cur.left
cur.left = rchild
rchild = cur.right
cur.right = pre
pre = cur
cur = tmp
return pre