[JAVA] Recursion / T : O(N), S : O(1)


  • 0
    J
    class Solution {
        public TreeNode addOneRow(TreeNode root, int v, int d) {
            if(d == 1){
                TreeNode node = new TreeNode(v);
                node.left = root;
                return node;
            }
            
            return addRow(root, v, d);
        }
        
        public TreeNode addRow(TreeNode root, int v, int d){
            if(root == null)
                return null;
            
            if(d == 2){
                TreeNode lnode = new TreeNode(v);
                lnode.left = root.left;
                TreeNode rnode = new TreeNode(v);
                rnode.right = root.right;
                
                root.left = lnode;
                root.right = rnode; 
                return root;
            }
            
            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.