Easy to understand java solution No compact No '?'


  • 0
    G
    public TreeNode addOneRow(TreeNode root, int v, int d) {
    		if(d==1){
    			TreeNode newroot = new TreeNode(v);
    			newroot.left = root;
    			return newroot;
    		}
    		
    		if(d==2 && root!=null){
    			
    			TreeNode newleft = new TreeNode(v);
    			TreeNode newright = new TreeNode(v);
    			if(root.left!=null){
    				TreeNode temp1 = root.left;
    				newleft.left = temp1;
    			}
    			if(root.right!=null){
    				TreeNode temp2 = root.right;
    				newright.right = temp2;
    			}
    			
    			root.left = newleft;
    			root.right = newright;
    			
    			return root;
    		}
    		if(root!=null){
        		addOneRow(root.left, v, d-1);
        	
        		addOneRow(root.right, v, d-1);
    		}
    		return root;
        }
    

Log in to reply
 

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