Skip to content

Latest commit

 

History

History
38 lines (28 loc) · 926 Bytes

623.-add-one-row-to-tree.md

File metadata and controls

38 lines (28 loc) · 926 Bytes

623. Add One Row to Tree

看到题目一开始就只能想到前序遍历或者层次遍历


# 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: TreeNode, v: int, d: int) -> TreeNode:
        
        if not root :
            return 
        
        if d == 1:
            new_r = TreeNode(v)
            new_r.left = root
            return new_r
        
        if d == 2:
            left = TreeNode(v)
            right = TreeNode(v)
            
            left.left = root.left
            right.right = root.right
            root.left = left
            root.right = right
            
        self.addOneRow(root.left, v , d - 1)
        self.addOneRow(root.right, v, d - 1)
        
        return root