515-Find Largest Value in Each Tree Row
Description
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]
問題描述
找出二叉樹每層中最大的值
問題分析
前序遍歷, 注意利用高度
解法1
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new ArrayList();
if (root == null) return res;
Queue<TreeNode> queue = new LinkedList();
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
int max = Integer.MIN_VALUE;
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
max = Math.max(max, node.val);
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
res.add(max);
}
return res;
}
}
解法2
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new ArrayList();
if(root == null) return res;
find(root, res, 0);
return res;
}
public void find(TreeNode root, List<Integer> res, int depth){
if(root == null) return;
if(depth >= res.size()) res.add(root.val);
else if(res.get(depth) < root.val) res.set(depth, root.val);
find(root.left, res, depth + 1);
find(root.right, res, depth + 1);
}
}
相關文章
- 623-Add One Row to Tree
- 513-Find Bottom Left Tree Value
- SCSS @eachCSS
- pymysql.err.OperationalError: (1136, “Column count doesn‘t match value count at row 1“)報錯反省。MySqlError
- Promise.each()Promise
- Laravel each () 方法Laravel
- jQuery $.each用法jQuery
- LeetCode Kth Largest Element in an ArrayLeetCode
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- for-each迴圈
- leetcode 368. Largest Divisible SubsetLeetCode
- 215. Kth Largest Element in an Array
- MySQL裡的found_row()與row_count()MySql
- A. Arrow a Row
- ORACLE ROW MOVEMENTOracle
- 對Largest函式的測試函式
- sass的迴圈for,while,eachWhile
- $.each()、$.map()區別淺談
- MySQL Binlogging Fails With Writing One Row To The Row-based Binary Log FailedMySqlAI
- 什麼是 Dynatrace 的 Largest Contentful PaintAI
- python leetcode 215. Kth Largest Element in an ArrayPythonLeetCode
- mysql 報錯:ERROR 1366 (HY000): Incorrect string value: ‘\xD5\xC5\xC8\xFD‘ for column ‘name‘ at row 1MySqlError
- Terraform中的for_each和countORM
- #1118 - Row size too large. The maximum row size for the used table type, not counting BLOBs
- 【MySQL報錯】1366 - Incorrect string value: ‘\xE6\x80\xBB\xE7\xBB\x8F...‘ for column ‘name‘ at row 1MySql
- [LeetCode] 2275. Largest Combination With Bitwise AND Greater Than ZeroLeetCode
- [leetcode] 1624. Largest Substring Between Two Equal CharactersLeetCode
- enq: TX - row lock contentionENQ
- [LeetCode] 2070. Most Beautiful Item for Each QueryLeetCode
- 116-Populating Next Right Pointers in Each Node
- golang multiple-value xxx in single-value contextGolangContext
- abc372E K-th Largest Connected Components
- Largest Submatrix of All 1’s(思維+單調棧)
- 【LEETCODE】模擬面試-215. Kth Largest EleLeetCode面試
- 976. Largest Perimeter Triangle(Leetcode每日一題-2020.11.29)LeetCode每日一題
- tree
- Flutter 之 Row、Column詳解Flutter
- flutter佈局-2-rowFlutter