Simple Java Solution without helper


  • 0
    Z
        public TreeNode addOneRow(TreeNode root, int v, int d) {
            if(root == null) return d == 1 ? new TreeNode(v) : null;
            // exception when d == 1, the root will be left node of new tree
            if(d == 1) {
                TreeNode tmp = new TreeNode(v);
                tmp.left = root;
                return tmp;
            }
            // when d == 2 it will be added as left and right of root
            if(d == 2) {
                TreeNode left = root.left;
                TreeNode right = root.right;
                root.left = new TreeNode(v);
                root.right= new TreeNode(v);
                root.left.left = left;
                root.right.right = right;
                return root;
            }
            // dfs when d > 2
            addOneRow(root.left, v, d - 1);
            addOneRow(root.right, v, d - 1);
            return root;
        }
    

    Let me know if this won't pass in the future. Thx.^^


Log in to reply
 

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