standard BFS in java


  • 5
    F
        public int findBottomLeftValue(TreeNode root) {
            /*any initial value is valid*/
            int result = -1;
            ArrayDeque<TreeNode> queue = new ArrayDeque<>();
            queue.offer(root);
            while (!queue.isEmpty()) {
                result = queue.peek().val;
                int size = queue.size();
                for (int i = 0; i < size; i++) {
                    TreeNode treeNode = queue.poll();
                    if (treeNode.left != null) {
                        queue.offer(treeNode.left);
                    }
                    if (treeNode.right != null) {
                        queue.offer(treeNode.right);
                    }
                }
            }
            return result;
        }
    

  • 0
    R

    hahaha,Your code is completely same to me

    public int findBottomLeftValue(TreeNode root) {
    		int left = root.val;
    		Queue<TreeNode> data = new LinkedList<>();
    		data.add(root);
    		while (!data.isEmpty()) {
    			left = data.peek().val;
    			int i = data.size();
    			while (i-- > 0) {
    				TreeNode temp = data.poll();
    				if (temp.left != null)
    					data.add(temp.left);
    				if (temp.right != null)
    					data.add(temp.right);
    			}
    		}
    		return left;
    	}
    

Log in to reply
 

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