Java short and easy to understand solution

  • 0
    public class Solution {
        public TreeNode addOneRow(TreeNode root, int v, int d) {
            return dfs(root, 1, v, d, true);
        private TreeNode dfs(TreeNode root, int curDepth, int v, int d, boolean isLeft) {
            if(curDepth == d) {
                TreeNode node = new TreeNode(v);
                if(isLeft) node.left = root;
                else node.right = root;
                return node;
            if(root == null) return null;
            root.left = dfs(root.left, curDepth+1, v, d, true);
            root.right = dfs(root.right, curDepth+1, v, d, false);
            return root;

Log in to reply

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