Add One Row to Tree

Description:

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.

Input: 
A binary tree as following:
      4
     /   
    2    
   / \   
  3   1    
v = 1
d = 3
Output: 
      4
     /   
    2
   / \    
  1   1
 /     \  
3       1
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode addOneRow(TreeNode root, int v, int d) {
        if(d==1){    //當只有一個根節點的情況
            TreeNode n = new TreeNode(v);
            n.left=root;
            return n;
        }
        insertOneRow(v,root,1,d);
        return root;
    }
    public void insertOneRow(int v,TreeNode root,int depth,int d){
        if(root==null) return;
        if(depth==(d-1)){
            TreeNode t=root.left;       //暫存需要插入的那一層的節點(根的左子節點)
            root.left=new TreeNode(v);    //插入新的左子節點
            root.left.left=t;            //鏈接原來的節點在新的節點之後
            t=root.right;                //暫存根的右子節點,重複上述操作
            root.right=new TreeNode(v);
            root.right.right=t;
        }else{
            insertOneRow(v,root.left,depth+1,d);    //不是第d-1層,遞歸進入右子樹
            insertOneRow(v,root.right,depth+1,d);
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章