Leetcode 623. Add One Row to Tree
【摘要】
题目链接:leetcode 623
Given the root of a binary tree, then value v and depth d, you need to add a r...
题目链接:leetcode 623
Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value v at the given depth d. The root node is at depth 1.
题目很简单,在树的第d层加一层,值为v。递归增加一层就好了。代码如下
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode addOneRow(TreeNode root, int v, int d) {
if (null == root)
return null;
if (1 == d) {
TreeNode left = new TreeNode(v);
left.left = root;
root = left;
}
else if (2 == d) {
TreeNode left = new TreeNode(v);
TreeNode right = new TreeNode(v);
left.left = root.left;
right.right = root.right;
root.left = left;
root.right = right;
}
else {
addOneRow(root.left, v, d-1);
addOneRow(root.right, v, d-1);
}
return root;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
文章来源: xindoo.blog.csdn.net,作者:xindoo,版权归原作者所有,如需转载,请联系作者。
原文链接:xindoo.blog.csdn.net/article/details/73743520
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)