515. Find Largest Value in Each Tree Row

来源:互联网 发布:java杨辉三角四行 编辑:程序博客网 时间:2024/05/18 02:07

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]
题意:找出二叉树中,每层节点中的最大值。

解题思路:
BFS(广度优先搜索),可以看做是层序遍历的扩展。由于层序遍历时,队列里并不能确定每层节点数,因此,只需要在层序遍历的过程中,引入一个值(queueSize)来标识每层节点数,然后利用for循环筛选出每层节点里的最大值即可。

public List<Integer> largestValues(TreeNode root) {        List<Integer> result = new ArrayList<Integer>();        if(root==null) return result;        if(root.left==null&&root.right==null) {            result.add(root.val);            return result;        }        //在常规层序遍历中,队列里并不能反映出每层节点数,        //因此需要一个queueSize变量来记录每层一共有几个节点        int queueSize = root == null? 0:1;        Queue<TreeNode> queue = new LinkedList<TreeNode>();        queue.offer(root);        while(!queue.isEmpty()){            int largestNode = Integer.MIN_VALUE;            for (int i = 0; i < queueSize; i++) {                TreeNode node = queue.poll();                largestNode = Math.max(largestNode, node.val);                if(node.left != null){                    queue.offer(node.left);                }                if(node.right != null){                    queue.offer(node.right);                }            }            queueSize = queue.size();            result.add(largestNode);        }        return result;    }
原创粉丝点击