​LeetCode刷题实战623:在二叉树中增加一行

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 在二叉树中增加一行,我们先来看题面:

https://leetcode.cn/problems/add-one-row-to-tree/

cbe17b74fc41a96169ff587d404889d1.png

给定一个二叉树的根 root 和两个整数 val 和 depth ,在给定的深度 depth 处添加一个值为 val 的节点行。
注意,根节点 root 位于深度 1 。
加法规则如下:


给定整数 depth,对于深度为 depth - 1 的每个非空树节点 cur ,创建两个值为 val 的树节点作为 cur 的左子树根和右子树根。
cur 原来的左子树应该是新的左子树根的左子树。
cur 原来的右子树应该是新的右子树根的右子树。
如果 depth == 1 意味着 depth - 1 根本没有深度,那么创建一个树节点,值 val 作为整个原始树的新根,而原始树就是新根的左子树。

示例

示例:

MyCircularQueue circularQueue = new MyCircularQueue(3); // 设置长度为 3
circularQueue.enQueue(1);  // 返回 true
circularQueue.enQueue(2);  // 返回 true
circularQueue.enQueue(3);  // 返回 true
circularQueue.enQueue(4);  // 返回 false,队列已满
circularQueue.Rear();  // 返回 3
circularQueue.isFull();  // 返回 true
circularQueue.deQueue();  // 返回 true
circularQueue.enQueue(4);  // 返回 true
circularQueue.Rear();  // 返回 4
 

提示:

所有的值都在 0 至 1000 的范围内;
操作数将在 1 至 1000 的范围内;
请不要使用内置的队列库。

示例

f69edf51082b15a96c0d55cdbe4f012c.png

8fd848837af9509838638797ebb86a0f.png

解题

https://www.cnblogs.com/zhengxch/p/14924672.html

解题思路:这道题目比较直接,好像并没有什么技巧,就是在二叉树深度遍历的时候,判断当前深度是否为depth-1,如果是,那就新增两个节点,赋值为val,增加到当前节点中,当前节点原来的左子树和右子树依次作为新左节点的左子树和新右节点的右子树即可。如果当前深度不为depth-1,那就对左子节点和右子节点分别调用递归函数,递归函数的参数中,深度递增,同时进入递归函数后,要判断当前节点是否为空,若为空,说明当前分支不能添加新节点,直接返回即可。

class Solution {
    public TreeNode addOneRow(TreeNode root, int val, int depth) {
        if(depth==1){
            TreeNode node = new TreeNode(val);
            node.left = root;
            return node;
        }
        helper(root, 1, depth, val);
        return root;
    }

    public void helper(TreeNode node, int curDepth, int depth, int val){
        if(node==null) return;
        if(curDepth==depth-1){
            TreeNode newLeftNode = new TreeNode(val);
            TreeNode leftTreeRoot = node.left;
            node.left = newLeftNode;
            newLeftNode.left = leftTreeRoot;
            TreeNode newRightNode = new TreeNode(val);
            TreeNode rightTreenode = node.right;
            node.right = newRightNode;
            newRightNode.right = rightTreenode; 
        }
        else{
            helper(node.left, curDepth+1, depth, val);
            helper(node.right, curDepth+1, depth, val);
        } 
    }
}

上期推文:

LeetCode1-620题汇总,希望对你有点帮助!

LeetCode刷题实战621:任务调度器

LeetCode刷题实战622:设计循环队列

d5c477bd15b675aaf018bc0ad8983413.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值