-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.py
67 lines (53 loc) · 1.88 KB
/
Solution.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
# 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 isLeafNode(self, node):
return not node.left and not node.right
def findLeftNodes(self, node, res):
if not node:
return
# avoid double count with leaf nodes
if not self.isLeafNode(node):
res.append(node.val)
if node.left:
self.findLeftNodes(node.left, res)
else:
self.findLeftNodes(node.right, res)
def findRightNodes(self, node, res):
if not node:
return
if node.right:
self.findRightNodes(node.right, res)
else:
self.findRightNodes(node.left, res)
# counterclockwise order and avoid double count with leaf nodes
if not self.isLeafNode(node):
res.append(node.val)
def findLeafNodes(self, node, res):
if not node:
return
# the current node is leaf node
if not node.left and not node.right:
res.append(node.val)
return
self.findLeafNodes(node.left, res)
self.findLeafNodes(node.right, res)
def boundaryOfBinaryTree(self, root: TreeNode) -> List[int]:
# error handling
if not root:
return []
res = []
# avoid double count in leafnode and left/right nodes
if root.left or root.right:
res.append(root.val)
self.findLeftNodes(root.left, res)
print("res:{}".format(res))
self.findLeafNodes(root, res)
print("res:{}".format(res))
self.findRightNodes(root.right , res)
print("res:{}".format(res))
return res