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]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.LinkedList;import java.util.List;import java.util.Queue;public class AverageLevelsBinaryTree {public static void main(String[] args) {TreeNode root = new TreeNode(3);root.left = new TreeNode(9);root.right = new TreeNode(20);root.right.left = new TreeNode(15);root.right.right = new TreeNode(7);List<Double> ave = averageOfLevels(root);System.out.println(Arrays.asList(ave));}// function to find the average of all// levelsstatic List<Double> averageOfLevels(TreeNode root) {List<Double> res = new ArrayList<Double>();if (root == null)return res;Queue<TreeNode> q = new LinkedList<TreeNode>();q.add(root);while (!q.isEmpty()) {int len = q.size();int n = len;long sum = 0;while (len > 0) {len--;TreeNode temp = q.poll();sum += temp.val;if (temp.left != null)q.add(temp.left);if (temp.right != null)q.add(temp.right);}double x = (double) sum / n;res.add(x);}return res;}}class TreeNode {int val;TreeNode left;TreeNode right;TreeNode() {}TreeNode(int val) {this.val = val;}TreeNode(int val, TreeNode left, TreeNode right) {this.val = val;this.left = left;this.right = right;}}
C++
#include <bits/stdc++.h>using namespace std;//struct for treenodestruct TreeNode{int data;TreeNode *left;TreeNode *right;TreeNode(int data){this->data = data;this->left = NULL;this->right = NULL;}};//function to find the average of all//levelsvector<double> averageOfLevels(TreeNode *root){vector<double> res;if (root == NULL)return res;queue<TreeNode *> q;q.push(root);while (!q.empty()){int len = q.size();int n = len;long long int sum = 0;while (len--){TreeNode *temp = q.front();q.pop();sum += temp->data;if (temp->left)q.push(temp->left);if (temp->right)q.push(temp->right);}double x = (double)sum / n;res.push_back(x);}return res;}int main(){TreeNode *root = new TreeNode(3);root->left = new TreeNode(9);root->right = new TreeNode(20);root->right->left = new TreeNode(15);root->right->right = new TreeNode(7);vector<double> ave = averageOfLevels(root);cout << "[";for (int i = 0; i < ave.size() - 1; i++)cout << ave[i] << ", ";cout << ave[ave.size() - 1] << "]";return 0;}
No comments:
Post a Comment