637-Average of Levels in Binary Tree
Description
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
Input:
3
/ \
9 20
/ \
15 7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
問題描述
給定二叉樹, 以陣列的形式返回其每層節點的平均值。(修改後返回值變成了List型別)
問題分析
通過深度遍歷來做, 關鍵是在遍歷的過程中利用好每個節點的depth
解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Double> averageOfLevels(TreeNode root) {
List<Integer> count = new ArrayList();
List<Double> res = new ArrayList();
average(root, 0, res, count);
for(int i = 0; i < res.size();i++) res.set(i, res.get(i) / count.get(i));
return res;
}
public void average(TreeNode t, int i, List<Double> sum, List<Integer> count) {
if (t == null) return;
if(i < sum.size()){
sum.set(i, sum.get(i) + t.val);
count.set(i, count.get(i) + 1);
}else{
sum.add(1.0 * t.val);
count.add(1);
}
average(t.left, i + 1, sum, count);
average(t.right, i + 1, sum, count);
}
}
相關文章
- Traversals of binary tree
- Leetcode Binary Tree PathsLeetCode
- [LintCode] Binary Tree Level Order
- 545. Boundary of Binary Tree
- 257. Binary Tree Paths
- Construct String from Binary TreeStruct
- [LintCode] Check Full Binary Tree
- 257-Binary Tree Paths
- 543-Diameter of Binary Tree
- 563-Binary Tree Tilt
- 655-Print Binary Tree
- 654-Maximum Binary Tree
- 814-Binary Tree Pruning
- 110-Balanced Binary Tree
- 226-Invert Binary Tree
- 104. Maximum Depth of Binary Tree
- LeetCode 543. Diameter of Binary TreeLeetCode
- Binary Tree Level Order Traversal [LEETCODE]LeetCode
- LeetCode545.Boundary-of-Binary-TreeLeetCode
- Leetcode 226. Invert Binary TreeLeetCode
- [leetcode]binary-tree-inorder-traversalLeetCode
- [leetcode]maximum-depth-of-binary-treeLeetCode
- 662. Maximum Width of Binary Tree
- 173. Binary Search Tree Iterator
- [LeetCode] 226. Invert Binary TreeLeetCode
- [LeetCode] 543. Diameter of Binary TreeLeetCode
- LeetCode之Univalued Binary Tree(Kotlin)LeetCodeKotlin
- LeetCode之Binary Tree Pruning(Kotlin)LeetCodeKotlin
- 111-Minimum Depth of Binary Tree
- 662-Maximum Width of Binary Tree
- Binary-tree-level-order-traversal
- 104-Maximum Depth of Binary Tree
- 669-Trim a Binary Search Tree
- LeetCode#110.Balanced Binary Tree(Tree/Height/DFS/Recursion)LeetCode
- LeetCode 104. Maximum Depth of Binary TreeLeetCode
- LeetCode 98. Validate Binary Search TreeLeetCode
- LeetCode | 144. Binary Tree Preorder TraversalLeetCode
- LeetCode | 145. Binary Tree Postorder TraversalLeetCode