forked from tiationg-kho/leetcode-pattern-500
-
Notifications
You must be signed in to change notification settings - Fork 0
/
545-boundary-of-binary-tree.py
48 lines (44 loc) · 1.38 KB
/
545-boundary-of-binary-tree.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
# Definition for a binary tree node.
# 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]:
root_list = []
left_list = []
leaf_list = []
right_list = []
def preorder(node, flag):
if not node:
return
elif not node.left and not node.right:
leaf_list.append(node.val)
elif flag == 0:
root_list.append(node.val)
preorder(node.left, 1)
preorder(node.right, 2)
elif flag == 1:
left_list.append(node.val)
preorder(node.left, 1)
preorder(node.right, 1 if not node.left else 3)
elif flag == 2:
right_list.append(node.val)
preorder(node.left, 2 if not node.right else 3)
preorder(node.right, 2)
else:
preorder(node.left, 3)
preorder(node.right, 3)
preorder(root, 0)
return root_list + left_list + leaf_list + right_list[::- 1]
# time O(n)
# space O(n)
# using tree and dfs (preorder and recursive) and record leaves
'''
flag
0 is root
1 is left boundary
2 is right boundary
3 is others
'''