[LeetCode] Find Largest Value in Each Tree Row

Find Largest Value in Each Tree Row

You need to find the largest value in each row of a binary tree.code

BFS

Time Complexity
O(N)
Space Complexity
O(N)it

思路

簡單的BFS,每層更新最大值放入resList

代碼

public List<Integer> largestValues(TreeNode root) {
    List<Integer> res = new ArrayList<Integer>();
    if(root == null) return res;
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.offer(root);
    while(!queue.isEmpty()){
        int size = queue.size();
        int max = Integer.MIN_VALUE;
        for(int i = 0; i < size; i++){
            TreeNode cur = queue.poll();
            max = Math.max(cur.val, max);
            if(cur.left != null){
                queue.offer(cur.left);
            }
            if(cur.right != null){
                queue.offer(cur.right);
            }
        }
        res.add(max);
    }
    return res;
}
相關文章
相關標籤/搜索