LeetCode 637. Average of Levels in Binary Tree

原题链接在这里:https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/

题目:

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].

Note:

  1. The range of node's value is in the range of 32-bit signed integer.

题解:

可以采用BFS通过queue的size结算每层level的个数. 挨个poll出来计算sum.

Time Complexity: O(n), n 是node 个数. 

Space: O(n).

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public List<Double> averageOfLevels(TreeNode root) {
12         List<Double> res = new ArrayList<Double>();
13         if(root == null){
14             return res;
15         }
16         
17         LinkedList<TreeNode> que = new LinkedList<TreeNode>();
18         que.add(root);
19         while(!que.isEmpty()){
20             int count = que.size();
21             double sum = 0.0;
22             for(int i = 0; i<count; i++){
23                 TreeNode tn = que.poll();
24                 sum += tn.val;
25                 if(tn.left != null){
26                     que.add(tn.left);
27                 }
28                 if(tn.right != null){
29                     que.add(tn.right);
30                 }
31             }
32             res.add(sum/count);
33         }
34         return res;
35     }
36 }

AC C++:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     vector<double> averageOfLevels(TreeNode* root) {
15         vector<double> res;
16         if(!root){
17             return res;
18         }
19 
20         queue<TreeNode*> que;
21         que.push(root);
22         while(!que.empty()){
23             int size = que.size();
24             double sum = 0.0;
25             for(int i = 0; i < size; i++){
26                 TreeNode* cur = que.front();
27                 que.pop();
28                 sum += cur->val;
29 
30                 if(cur->left){
31                     que.push(cur->left);
32                 }
33 
34                 if(cur->right){
35                     que.push(cur->right);
36                 }
37             }
38 
39             res.push_back(sum / size);
40         }
41 
42         return res;
43     }
44 };

AC Python:

 1 # Definition for a binary tree node.
 2 # class TreeNode:
 3 #     def __init__(self, val=0, left=None, right=None):
 4 #         self.val = val
 5 #         self.left = left
 6 #         self.right = right
 7 class Solution:
 8     def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
 9         res = []
10         if not root:
11             return res
12         
13         que = deque([root])
14         while que:
15             size = len(que)
16             sum = 0
17             for i in range(size):
18                 cur = que.popleft()
19                 sum += cur.val
20                 if cur.left:
21                     que.append(cur.left)
22                 if cur.right:
23                     que.append(cur.right)
24                 
25             res.append(sum / size)
26 
27         return res
28         

也可以使用DFS. create 新的class Node 来维护每层的sum 和count.

Time Complexity: O(n). Space: O(logn).

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     class Node{
12         double sum;
13         int count;
14         Node(double sum, int count){
15             this.sum = sum;
16             this.count = count;
17         }
18     }
19     
20     public List<Double> averageOfLevels(TreeNode root) {
21         List<Double> res = new ArrayList<Double>();
22         List<Node> nodes = new ArrayList<Node>();
23         
24         avaerageOfLevelsDfs(root, nodes, 0);
25         for(int i = 0; i<nodes.size(); i++){
26             res.add(nodes.get(i).sum/nodes.get(i).count);
27         }
28         return res;
29     }
30     
31     private void avaerageOfLevelsDfs(TreeNode root,  List<Node> nodes, int level){
32         if(root == null){
33             return;
34         }
35         
36         if(level == nodes.size()){
37             nodes.add(new Node(1.0 * root.val, 1));
38         }else{
39             nodes.get(level).sum += root.val;
40             nodes.get(level).count++;
41         }
42         
43         avaerageOfLevelsDfs(root.left, nodes, level+1);
44         avaerageOfLevelsDfs(root.right, nodes, level+1);
45     }
46 }

 

posted @ 2017-09-12 01:59  Dylan_Java_NYC  阅读(348)  评论(0编辑  收藏  举报