频道栏目
首页 > 资讯 > 其他综合 > 正文

623. Add One Row to Tree“编程题”

17-11-27        来源:[db:作者]  
收藏   我要投稿

1.题目
?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.

The adding rule is: given a positive integer depth d, for each NOT null tree nodes N in depth d-1, create two tree nodes with value v as N’s left subtree root and right subtree root. And N’s original left subtree should be the left subtree of the new left subtree root, its original right subtree should be the right subtree of the new right subtree root. If depth d is 1 that means there is no depth d-1 at all, then create a tree node with value v as the new root of the whole original tree, and the original tree is the new root’s left subtree.

Example 1:
Input:
A binary tree as following:
4
/ \
2 6
/ \ /
3 1 5

v = 1

d = 2

Output:
4
/ \
1 1
/ \
2 6
/ \ /
3 1 5

Example 2:
Input:
A binary tree as following:
4
/
2
/ \
3 1

v = 1

d = 3

Output:
4
/
2
/ \
1 1
/ \
3 1
Note:
The given d is in range [1, maximum depth of the given tree + 1].
The given binary tree has at least one tree node.

2.分析
? 这道题,主要考察二叉树与递归的思想。
3.解题

public TreeNode addOneRow(TreeNode root, int v, int d) {
    // 边界处理
    if(root==null || d<1){
        return root;
    }
    if(d==1){
        TreeNode node = new TreeNode(v);
        node.left = root;
        return node;
    }
    Stackstack_one = new Stack<>();
    Stackstack_two = new Stack<>();
    // TreeNode origin = root;
    stack_one.push(root);
    int dep = 0;
    while(!stack_one.isEmpty()  || !stack_two.isEmpty()){
        if(!stack_one.isEmpty() && stack_two.isEmpty()){
            dep++;
            while(!stack_one.isEmpty()){
                if(dep

4.总结 ? 我这里是利用栈的特性实现递归,空间开销增大了,看到别人直接递归调用,思想其实万变不离其中,都是一样。

相关TAG标签
上一篇:Android媒体播放功能曝出安全漏洞,或将导致攻击者可记录音频或屏幕
下一篇:适配之em和rem的使用、绝对适配方案、Media Queries讲解
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站