Pretty straightforward Java solution


  • 0
    K
    public class Solution {
        public TreeNode addOneRow(TreeNode root, int v, int d) {
            return addOneRow(root, true, v, d, 1);
        }
        
        public TreeNode addOneRow(TreeNode node, boolean left, int v, int d, 
                   int depth) {
            if(depth == d) {
                TreeNode newNode = new TreeNode(v);
                if(left) {
                    newNode.left = node;
                } else {
                    newNode.right = node;
                }
                
                return newNode;
            } else if(node != null) {
                node.left = addOneRow(node.left, true, v, d, depth + 1);
                node.right = addOneRow(node.right, false, v, d, depth + 1);
            }
            
            return node;
        }
    }
    

Log in to reply
 

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