-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind_all_the_lonely_nodes.py
50 lines (31 loc) · 1.21 KB
/
find_all_the_lonely_nodes.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
'''
In a binary tree, a lonely node is a node that is the only child of its parent node. The root of the tree is not lonely
because it does not have a parent node.
Given the root of a binary tree, return an array containing the values of all lonely nodes in the tree. Return the list in any order.
'''
# 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 getLonelyNodes(self, root: Optional[TreeNode]) -> List[int]:
total = list()
def dfs(root):
if not root:
return
if not root.left and not root.right:
return
elif root.left and not root.right:
total.append(root.left.val)
dfs(root.left)
elif root.right and not root.left:
total.append(root.right.val)
dfs(root.right)
else:
dfs(root.left)
dfs(root.right)
dfs(root)
print(total)
return total