Simple Java solution O(n)


  • 0
    Z
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode addOneRow(TreeNode root, int v, int d) {
            if (root == null)
                return null;
            if (d > 2) {
                addOneRow(root.left, v, d-1);
                addOneRow(root.right, v, d-1);
            } else if (d == 2){
                 TreeNode newLeft = new TreeNode(v);
                 TreeNode newRight = new TreeNode(v);
                 newLeft.left = root.left;
                 newRight.right = root.right;
                 root.left = newLeft;
                 root.right = newRight;
            } else if (d == 1) {
                TreeNode newRoot = new TreeNode(v);
                newRoot.left = root;
                root = newRoot;
            }
            return root;
        }
    }

Log in to reply
 

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