Java BFS Iterative


  • 0
    R
    public TreeNode addOneRow(TreeNode root, int v, int d) {
            if (d==1) {
                TreeNode newRoot = new TreeNode(v);
                newRoot.left = root;
                return newRoot;
            }
            Queue<TreeNode> queue = new LinkedList<>();
            int depth = 0;
            queue.offer(root);
            while(!queue.isEmpty()){
                depth ++;
                int size = queue.size();
                for (int i=0;i<size;i++){
                    TreeNode cur = queue.poll();
                    if (depth == d-1){
                        TreeNode oldLeft = cur.left;
                        cur.left = new TreeNode(v);
                        cur.left.left = oldLeft;
                        TreeNode oldRight = cur.right;
                        cur.right = new TreeNode(v);
                        cur.right.right = oldRight;
                    }
                    if (cur.left != null) queue.offer(cur.left);
                    if (cur.right != null) queue.offer(cur.right);
                }
            }
            return root;
        }
    

Log in to reply
 

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