JAVA, Iterative


  • 0
    public TreeNode addOneRow(TreeNode root, int v, int d) {
            if(d == 1) {
                TreeNode new_root = new TreeNode(v);
                new_root.left = root;
                return new_root;
            }
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            int level = 1;
            while(++level < d) {
                int size = queue.size();
                while(size-- > 0) {
                    TreeNode cur = queue.poll();
                    if(cur.left != null) queue.add(cur.left);
                    if(cur.right != null) queue.add(cur.right);
                }
            }
            while(!queue.isEmpty()) {
                TreeNode cur = queue.poll();
                TreeNode temp_left = cur.left;
                TreeNode temp_right = cur.right;
                cur.left = new TreeNode(v);
                cur.left.left = temp_left;
                cur.right = new TreeNode(v);
                cur.right.right = temp_right;
            }
            return root;
        }
    

Log in to reply
 

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