-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathadd.py
More file actions
53 lines (46 loc) · 1.8 KB
/
add.py
File metadata and controls
53 lines (46 loc) · 1.8 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
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def addOneRow(self, root, v, d):
"""
:type root: TreeNode
:type v: int
:type d: int
:rtype: TreeNode
"""
# Logic: 40ms 97% --> get to the correct depth insert based on the parent and current node (create a new node and then insert)
def getToDepthAndInsert(node, current_depth, parent):
# If the current depth is reached, then create new node
if current_depth == d:
new_node = TreeNode(v)
# * If the corresponding depth is greater than the leaf, then add as leaf
# * Else, insert in between
if not node:
if not parent.left:
parent.left = new_node
elif not parent.right:
parent.right = new_node
else:
if parent.left == node:
parent.left = new_node
new_node.left = node
else:
parent.right = new_node
new_node.right = node
else:
# If depth is not reached, recurse
if node:
getToDepthAndInsert(node.left, current_depth+1, node)
getToDepthAndInsert(node.right, current_depth+1, node)
# Depth being the root itself
if d == 1:
new_node = TreeNode(v)
new_node.left = root
root = new_node
else:
getToDepthAndInsert(root, 1, None)
return root