623. Add One Row to Tree
https://leetcode.com/problems/add-one-row-to-tree/
Python
- Edge case很多,要多思考一下
- depth == 1
- depth == max_tree_depth
class Solution:
def addOneRow(self, root: Optional[TreeNode], val: int, depth: int) -> Optional[TreeNode]:
if depth == 1:
return TreeNode(val=val, left=root)
def dfs(node, level, direction):
if not node:
return None if level != depth else TreeNode(val=val)
if level != depth:
node.left = dfs(node.left, level+1, 'L')
node.right = dfs(node.right, level+1, 'R')
return node
return TreeNode(
val=val,
left=dfs(node, level+2, 'L') if direction == 'L' else None,
right=dfs(node, level+2, 'R') if direction == 'R' else None
)
root.left = dfs(root.left, 2, 'L')
root.right = dfs(root.right, 2, 'R')
return root