列表

详情


LCP 67. 装饰树

力扣嘉年华上的 DIY 手工展位准备了一棵缩小版的 二叉 装饰树 root 和灯饰,你需要将灯饰逐一插入装饰树中,要求如下:

现给定二叉树的根节点 root ,请返回完成装饰后的树的根节点。 示例 1:

输入: root = [7,5,6]

输出:[7,-1,-1,5,null,null,6]

解释:如下图所示, image.png{:width=400px}

示例 2:

输入: root = [3,1,7,3,8,null,4]

输出:[3,-1,-1,1,null,null,7,-1,-1,null,-1,3,null,null,8,null,4]

解释:如下图所示 image.png{:width=500px}

提示:

0 <= root.Val <= 1000 root 节点数量范围为 [1, 10^5]

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* expandBinaryTree(TreeNode* root) { } };

python3 解法, 执行用时: 532 ms, 内存消耗: 43.7 MB, 提交时间: 2022-11-10 16:57:25

# 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 expandBinaryTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root.left: root.left = TreeNode(-1, left=self.expandBinaryTree(root.left))
        if root.right: root.right = TreeNode(-1, right=self.expandBinaryTree(root.right))
        return root

python3 解法, 执行用时: 492 ms, 内存消耗: 43.8 MB, 提交时间: 2022-11-10 16:56:46

# 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 expandBinaryTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        def dfs(father: TreeNode):
            origin_left = father.left
            origin_right = father.right
            if origin_left is not None:
                father.left = TreeNode(val=-1, left=origin_left)
                dfs(origin_left)
            if origin_right is not None:
                father.right = TreeNode(val=-1, right=origin_right)
                dfs(origin_right)

        dfs(root)
        return root

上一题