-
Notifications
You must be signed in to change notification settings - Fork 0
/
0545.boundary-of-binary-tree.py
58 lines (49 loc) · 1.64 KB
/
0545.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
49
50
51
52
53
54
55
56
57
58
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def boundaryOfBinaryTree(self, root: TreeNode) -> List[int]:
def isLeaf(node:TreeNode) -> bool:
return node.left is None and node.right is None
def recursiveLeft(node:TreeNode):
if node is None:
return
if isLeaf(node):
return
self.result.append(node.val)
if node.left:
recursiveLeft(node.left)
else:
recursiveLeft(node.right)
def recursiveRight(node:TreeNode):
if node is None:
return
if isLeaf(node):
return
if node.right:
recursiveRight(node.right)
else:
recursiveRight(node.left)
# print("right val=", node.val)
self.result.append(node.val)
def recursiveLeaf(node:TreeNode):
if node is None:
return
if isLeaf(node):
# print("leaf val=", node.val)
self.result.append(node.val)
recursiveLeaf(node.left)
recursiveLeaf(node.right)
if root is None:
return []
self.result = [root.val]
if root.left:
recursiveLeft(root.left)
if root.left or root.right:
recursiveLeaf(root)
if root.right:
recursiveRight(root.right)
return self.result