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 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;
    }
}
发布了236 篇原创文章 · 获赞 577 · 访问量 52万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 猿与汪的秘密 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览