给定一个二叉树的根 root 和两个整数 val 和 depth ,在给定的深度 depth 处添加一个值为 val 的节点行。
注意,根节点 root 位于深度 1 。
加法规则如下:
给定整数 depth,对于深度为 depth - 1 的每个非空树节点 cur ,创建两个值为 val 的树节点作为 cur 的左子树根和右子树根。
cur 原来的左子树应该是新的左子树根的左子树。
cur 原来的右子树应该是新的右子树根的右子树。
如果 depth == 1 意味着 depth - 1 根本没有深度,那么创建一个树节点,值 val 作为整个原始树的新根,而原始树就是新根的左子树。来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/add-one-row-to-tree
此该题类似:算法学习:LeetCode-1161. 最大层内元素和
用队列存储元素,每一层遍历完后depth--,最后depth-1==0时说明到达需要添加元素的层次;
注意添加规则:该层的所有元素都添加,左右节点幼有添加要求;
需要depth=2时才可以进行插入新节点

- class Solution {
- public:
- TreeNode* addOneRow(TreeNode* root, int val, int depth) {
- if(root == nullptr){
- return nullptr;
- }
- if(depth==1){
- return new TreeNode(val, root, nullptr); //1.匿名类
- }
- depth--;
- queue
q1; - q1.push(root);
- while(!q1.empty()){
- int n=q1.size();
- depth--;
- while(n--){
- TreeNode* t=q1.front();//2.1队列的队头元素
- q1.pop(); //2.2队列pop无返回类型
- if(depth==0){
- TreeNode *p1=new TreeNode(val, t->left, nullptr);//3.注意这种构造方法
- TreeNode *p2=new TreeNode(val, nullptr,t->right);
- TreeNode* preLeft=t->left;
- t->left=p1;
- p1->left=preLeft;
- TreeNode* preRight=t->right;
- t->right=p2;
- p2->right=preRight;
- }
- if(t->left){
- q1.push(t->left);
- }
- if(t->right){
- q1.push(t->right);
- }
- }
- }
- return root;
- }
- };