-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0545-boundary-of-binary-tree.py
More file actions
69 lines (56 loc) · 1.79 KB
/
0545-boundary-of-binary-tree.py
File metadata and controls
69 lines (56 loc) · 1.79 KB
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
from typing import List, Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def boundaryOfBinaryTree(self, root: Optional[TreeNode]) -> List[int]:
if root is None:
return []
result = []
def isLeaf(node: Optional[TreeNode]) -> bool:
nonlocal result
if node is None:
return False
if node.left is None and node.right is None:
return True
def addLeftBound(node: TreeNode):
nonlocal result
while node:
if not isLeaf(node):
result.append(node.val)
if node.left:
node = node.left
else:
node = node.right
def addRightBound(node: TreeNode):
nonlocal result
stack = []
while node:
if not isLeaf(node):
stack.append(node.val)
if node.right:
node = node.right
else:
node = node.left
result += stack[::-1]
def addLeaf(node: TreeNode):
nonlocal result
if node:
if isLeaf(node):
result.append(node.val)
else:
addLeaf(node.left)
addLeaf(node.right)
if not isLeaf(root):
result.append(root.val)
addLeftBound(root.left)
addLeaf(root)
addRightBound(root.right)
return result
root = TreeNode(1)
root.right = TreeNode(2)
root.right.left = TreeNode(3)
root.right.right = TreeNode(4)
print(Solution().boundaryOfBinaryTree(root))