share my solution, using DFS!


  • 0
    T
    /**
     * 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(d==1){
                TreeNode Node=new TreeNode(v);
                Node.left=root;
                return Node;
            }
            
            addTreeNode(root,v,d-1,1);
            return root;
        }
        
        public void addTreeNode(TreeNode root,int v,int d,int level){
            if(d==level){
                  TreeNode left=new TreeNode(v);
                  TreeNode right=new TreeNode(v);
                  
                  TreeNode temp=root.left;
                  root.left=left;
                  left.left=temp;
                  temp=root.right;
                  root.right=right;
                  right.right=temp;
                  
            }else{ 
               
               if(root.left!=null){
                addTreeNode(root.left,v,d,level+1);
               }
               if(root.right!=null){
                   addTreeNode(root.right,v,d,level+1);
               }
                
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.