算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 在二叉树中增加一行,我们先来看题面:
https://leetcode.cn/problems/add-one-row-to-tree/
给定一个二叉树的根 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 的范围内;
请不要使用内置的队列库。
示例
解题
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);
}
}
}
上期推文: