leetcode515: Find Largest Value in Each Tree Row

来源:互联网 发布:猫腻最好看的小说 知乎 编辑:程序博客网 时间:2024/04/29 15:56

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

Example:

Input:           1         / \        3   2       / \   \        5   3   9 Output: [1, 3, 9]
广度优先搜索用队列,深度优先搜索用堆栈(还有,程序第三行在eclipse中会报错,leetcode上可以运行)

    public List<Integer> largestValues(TreeNode root) {        List<Integer> list = new ArrayList<Integer>();        Queue<TreeNode> queue = new LinkedList<>();        if(root != null)           queue.offer(root);        while(!queue.isEmpty()) {            int max = queue.peek().val;            int size = queue.size();            for(int i = 0; i < size; i++) {                TreeNode node = queue.poll();                max = Math.max(max, node.val);                if(node.right != null)                    queue.offer(node.right);                if(node.left != null)                    queue.offer(node.left);            }            list.add(max);        }                return list;    }



0 0