返回介绍

solution / 0600-0699 / 0637.Average of Levels in Binary Tree / README_EN

发布于 2024-06-17 01:03:36 字数 11113 浏览 0 评论 0 收藏 0

637. Average of Levels in Binary Tree

中文文档

Description

Given the root of a binary tree, return _the average value of the nodes on each level in the form of an array_. Answers within 10<sup>-5</sup> of the actual answer will be accepted.

 

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: [3.00000,14.50000,11.00000]
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].

Example 2:

Input: root = [3,9,20,15,7]
Output: [3.00000,14.50000,11.00000]

 

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -231 <= Node.val <= 231 - 1

Solutions

Solution 1

# Definition for a binary tree node.
# class TreeNode:
#   def __init__(self, val=0, left=None, right=None):
#     self.val = val
#     self.left = left
#     self.right = right
class Solution:
  def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
    q = deque([root])
    ans = []
    while q:
      s, n = 0, len(q)
      for _ in range(n):
        root = q.popleft()
        s += root.val
        if root.left:
          q.append(root.left)
        if root.right:
          q.append(root.right)
      ans.append(s / n)
    return ans
/**
 * Definition for a binary tree node.
 * public 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;
 *   }
 * }
 */
class Solution {
  public List<Double> averageOfLevels(TreeNode root) {
    List<Double> ans = new ArrayList<>();
    Deque<TreeNode> q = new ArrayDeque<>();
    q.offer(root);
    while (!q.isEmpty()) {
      int n = q.size();
      long s = 0;
      for (int i = 0; i < n; ++i) {
        root = q.pollFirst();
        s += root.val;
        if (root.left != null) {
          q.offer(root.left);
        }
        if (root.right != null) {
          q.offer(root.right);
        }
      }
      ans.add(s * 1.0 / n);
    }
    return ans;
  }
}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *   int val;
 *   TreeNode *left;
 *   TreeNode *right;
 *   TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *   TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *   TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
  vector<double> averageOfLevels(TreeNode* root) {
    queue<TreeNode*> q{{root}};
    vector<double> ans;
    while (!q.empty()) {
      int n = q.size();
      long long s = 0;
      for (int i = 0; i < n; ++i) {
        root = q.front();
        q.pop();
        s += root->val;
        if (root->left) q.push(root->left);
        if (root->right) q.push(root->right);
      }
      ans.push_back(s * 1.0 / n);
    }
    return ans;
  }
};
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */
func averageOfLevels(root *TreeNode) []float64 {
  q := []*TreeNode{root}
  ans := []float64{}
  for len(q) > 0 {
    n := len(q)
    s := 0
    for i := 0; i < n; i++ {
      root = q[0]
      q = q[1:]
      s += root.Val
      if root.Left != nil {
        q = append(q, root.Left)
      }
      if root.Right != nil {
        q = append(q, root.Right)
      }
    }
    ans = append(ans, float64(s)/float64(n))
  }
  return ans
}
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//   TreeNode {
//     val,
//     left: None,
//     right: None
//   }
//   }
// }
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::VecDeque;
impl Solution {
  pub fn average_of_levels(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<f64> {
    if root.is_none() {
      return Vec::new();
    }

    let mut q = VecDeque::new();
    q.push_back(Rc::clone(&root.unwrap()));
    let mut ans = Vec::new();
    while !q.is_empty() {
      let n = q.len();
      let mut sum = 0.0;
      for _ in 0..n {
        let node = q.pop_front().unwrap();
        sum += node.borrow().val as f64;
        if node.borrow().left.is_some() {
          q.push_back(Rc::clone(node.borrow().left.as_ref().unwrap()));
        }
        if node.borrow().right.is_some() {
          q.push_back(Rc::clone(node.borrow().right.as_ref().unwrap()));
        }
      }
      ans.push(sum / (n as f64));
    }
    ans
  }
}
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *   this.val = (val===undefined ? 0 : val)
 *   this.left = (left===undefined ? null : left)
 *   this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var averageOfLevels = function (root) {
  let q = [root];
  let ans = [];
  while (q.length) {
    const n = q.length;
    let s = 0;
    for (let i = 0; i < n; ++i) {
      root = q.shift();
      s += root.val;
      if (root.left) {
        q.push(root.left);
      }
      if (root.right) {
        q.push(root.right);
      }
    }
    ans.push(s / n);
  }
  return ans;
};

Solution 2

# Definition for a binary tree node.
# class TreeNode:
#   def __init__(self, val=0, left=None, right=None):
#     self.val = val
#     self.left = left
#     self.right = right
class Solution:
  def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
    def dfs(root, i):
      if root is None:
        return
      if len(s) == i:
        s.append([root.val, 1])
      else:
        s[i][0] += root.val
        s[i][1] += 1
      dfs(root.left, i + 1)
      dfs(root.right, i + 1)

    s = []
    dfs(root, 0)
    return [a / b for a, b in s]
/**
 * Definition for a binary tree node.
 * public 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;
 *   }
 * }
 */
class Solution {
  private List<Long> s = new ArrayList<>();
  private List<Integer> cnt = new ArrayList<>();

  public List<Double> averageOfLevels(TreeNode root) {
    dfs(root, 0);
    List<Double> ans = new ArrayList<>();
    for (int i = 0; i < s.size(); ++i) {
      ans.add(s.get(i) * 1.0 / cnt.get(i));
    }
    return ans;
  }

  private void dfs(TreeNode root, int i) {
    if (root == null) {
      return;
    }
    if (s.size() == i) {
      s.add((long) root.val);
      cnt.add(1);
    } else {
      s.set(i, s.get(i) + root.val);
      cnt.set(i, cnt.get(i) + 1);
    }
    dfs(root.left, i + 1);
    dfs(root.right, i + 1);
  }
}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *   int val;
 *   TreeNode *left;
 *   TreeNode *right;
 *   TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *   TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *   TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

using ll = long long;

class Solution {
public:
  vector<ll> s;
  vector<int> cnt;

  vector<double> averageOfLevels(TreeNode* root) {
    dfs(root, 0);
    vector<double> ans(s.size());
    for (int i = 0; i < s.size(); ++i) {
      ans[i] = (s[i] * 1.0 / cnt[i]);
    }
    return ans;
  }

  void dfs(TreeNode* root, int i) {
    if (!root) return;
    if (s.size() == i) {
      s.push_back(root->val);
      cnt.push_back(1);
    } else {
      s[i] += root->val;
      cnt[i]++;
    }
    dfs(root->left, i + 1);
    dfs(root->right, i + 1);
  }
};
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */
func averageOfLevels(root *TreeNode) []float64 {
  s := []int{}
  cnt := []int{}
  var dfs func(root *TreeNode, i int)
  dfs = func(root *TreeNode, i int) {
    if root == nil {
      return
    }
    if len(s) == i {
      s = append(s, root.Val)
      cnt = append(cnt, 1)
    } else {
      s[i] += root.Val
      cnt[i]++
    }
    dfs(root.Left, i+1)
    dfs(root.Right, i+1)
  }
  dfs(root, 0)
  ans := []float64{}
  for i, t := range s {
    ans = append(ans, float64(t)/float64(cnt[i]))
  }
  return ans
}
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *   this.val = (val===undefined ? 0 : val)
 *   this.left = (left===undefined ? null : left)
 *   this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var averageOfLevels = function (root) {
  let s = [];
  let cnt = [];
  function dfs(root, i) {
    if (!root) {
      return;
    }
    if (s.length == i) {
      s.push(root.val);
      cnt.push(1);
    } else {
      s[i] += root.val;
      cnt[i]++;
    }
    dfs(root.left, i + 1);
    dfs(root.right, i + 1);
  }
  dfs(root, 0);
  let ans = [];
  for (let i = 0; i < s.length; ++i) {
    ans.push(s[i] / cnt[i]);
  }
  return ans;
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文