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
- LeetCode-515. Find Largest Value in Each Tree Row (JAVA)(二叉树每行的最大值)
- 【LeetCode515 Find Largest Value in Each Tree Row】二叉树每行的最大值
- LeetCode 515. Find Largest Value in Each Tree Row
- LeetCode OJ 515. Find Largest Value in Each Tree Row
- LeetCode笔记:515. Find Largest Value in Each Tree Row
- [leetcode] 515. Find Largest Value in Each Tree Row
- 【LeetCode】515. Find Largest Value in Each Tree Row
- LeetCode;515. Find Largest Value in Each Tree Row
- leetcode 515. Find Largest Value in Each Tree Row
- leetcode 515. Find Largest Value in Each Tree Row
- leetcode-515. Find Largest Value in Each Tree Row
- leetcode 515. Find Largest Value in Each Tree Row
- leetcode 515. Find Largest Value in Each Tree Row
- leetcode 515. Find Largest Value in Each Tree Row
- LeetCode 515. Find Largest Value in Each Tree Row (C++)
- leetcode 515. Find Largest Value in Each Tree Row
- LeetCode#515. Find Largest Value in Each Tree Row
- leetcode 515. Find Largest Value in Each Tree Row
- NGINX
- POJ 3190 Stall Reservations
- waitKey (x)的两个作用
- codeforces710c Magic Odd Square
- 题目1107:搬水果
- LeetCode-515. Find Largest Value in Each Tree Row (JAVA)(二叉树每行的最大值)
- [Lpp]PHP的文件处理系统
- 继承ArrayAdapter类的实例
- UDP协议的客户机和服务器通信
- 13:最大上升子序列和
- Ubuntu命令笔记
- HDU
- 工厂方法模式与抽象工厂模式
- **APK瘦身**