-
Notifications
You must be signed in to change notification settings - Fork 84
/
623_Add_One_Row_to_Tree.py
36 lines (28 loc) · 1.08 KB
/
623_Add_One_Row_to_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
# 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 addOneRow(self, root: Optional[TreeNode], val: int, depth: int) -> Optional[TreeNode]:
if depth == 1:
newRoot = TreeNode(val)
newRoot.left = root
return newRoot
def traverse(root, curDepth, reqDepth):
if root is None:
return
if curDepth == reqDepth-1:
temp = root.left
root.left = TreeNode(val)
root.left.left = temp
temp = root.right
root.right = TreeNode(val)
root.right.right = temp
return
traverse(root.left, curDepth+1, reqDepth)
traverse(root.right, curDepth+1, reqDepth)
return
traverse(root, 1, depth)
return root