Easy java solution


  • 0
    H
    public TreeNode addOneRow(TreeNode root, int v, int d) {
            if (d == 1) {
                TreeNode newT = new TreeNode(v);
                newT.left = root;
                return newT;
            }
            dfs(root, d - 1, 1, v);
            return root;
        }
        
        public TreeNode dfs(TreeNode root, int depth, int index, int v) {
            if (root == null) {
                return null;
            }
            if (index == depth) {
                TreeNode newLeft = new TreeNode(v);
                TreeNode newRight = new TreeNode(v);
                TreeNode left = dfs(root.left, depth, index + 1, v);
                TreeNode right = dfs(root.right, depth, index + 1, v);
                root.left = newLeft;
                root.right = newRight;
                newLeft.left = left;
                newRight.right = right;
            } else {
                dfs(root.left, depth, index + 1, v);
                dfs(root.right, depth, index + 1, v);
            }
            return root;
        }
    

Log in to reply
 

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