LeetCode-515. Find Largest Value in Each Tree Row (JAVA)(二叉树每行的最大值)

来源:互联网 发布:生命之花 伤感网络歌曲 编辑:程序博客网 时间:2024/06/06 04:11

515. Find Largest Value in Each Tree Row

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解法

题目很简单,只需要记录每层的节点数木,并且记录最大值即可,思想是按照行打印二叉树

public List<Integer> largestValues(TreeNode root) {List<Integer> ret = new ArrayList<>();if (root == null)return ret;bfs(root, ret);return ret;}private void bfs(TreeNode root, List<Integer> ret) {Queue<TreeNode> q = new LinkedList<>();q.add(root);// 层次遍历,只需要记录本层结点个数即可int curNum = 1;// 下一层的节点数int nextNum = 0;int max = Integer.MIN_VALUE;while (!q.isEmpty()) {TreeNode node = q.poll();curNum--;max = Math.max(max, node.val);if (node.left != null) {q.offer(node.left);nextNum++;}if (node.right != null) {q.offer(node.right);nextNum++;}if (curNum == 0) {ret.add(max);curNum = nextNum;nextNum = 0;max = Integer.MIN_VALUE;}}}

discuss中前序遍历递归解法

Just a simple pre-order traverse idea(DFS). Use depth to expand result list  size and put the max value in the appropriate position.

public List<Integer> largestValues(TreeNode root) {List<Integer> res = new ArrayList<Integer>();preorder(root, res, 0);return res;}private void preorder(TreeNode root, List<Integer> res, int d) {if (root == null) {return;}// expand list sizeif (d == res.size()) {res.add(root.val);} else {// or set valueres.set(d, Math.max(res.get(d), root.val));}preorder(root.left, res, d + 1);preorder(root.right, res, d + 1);}


0 0
原创粉丝点击