Skip to content

feat: update solutions to lc problem: No.637 #3122

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 44 additions & 34 deletions solution/0600-0699/0637.Average of Levels in Binary Tree/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ tags:

### 方法一:BFS

我们可以使用广度优先搜索的方法,遍历每一层的节点,计算每一层的平均值。

具体地,我们定义一个队列 $q$,初始时将根节点加入队列。每次将队列中的所有节点取出,计算这些节点的平均值,加入答案数组中,并将这些节点的子节点加入队列。重复这一过程,直到队列为空。

时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点个数。

<!-- tabs:start -->

#### Python3
Expand Down Expand Up @@ -159,8 +165,12 @@ public:
root = q.front();
q.pop();
s += root->val;
if (root->left) q.push(root->left);
if (root->right) q.push(root->right);
if (root->left) {
q.push(root->left);
}
if (root->right) {
q.push(root->right);
}
}
ans.push_back(s * 1.0 / n);
}
Expand Down Expand Up @@ -227,29 +237,30 @@ func averageOfLevels(root *TreeNode) []float64 {
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 ans = vec![];
let mut q = VecDeque::new();
q.push_back(Rc::clone(&root.unwrap()));
let mut ans = Vec::new();
if let Some(root_node) = root {
q.push_back(root_node);
}
while !q.is_empty() {
let n = q.len();
let mut sum = 0.0;
let mut s: i64 = 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()));
if let Some(node) = q.pop_front() {
let node_borrow = node.borrow();
s += node_borrow.val as i64;
if let Some(left) = node_borrow.left.clone() {
q.push_back(left);
}
if let Some(right) = node_borrow.right.clone() {
q.push_back(right);
}
}
}
ans.push(sum / (n as f64));
ans.push((s as f64) / (n as f64));
}
ans
}
Expand All @@ -276,18 +287,15 @@ var averageOfLevels = function (root) {
const ans = [];
while (q.length) {
const n = q.length;
const nq = [];
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);
}
for (const { val, left, right } of q) {
s += val;
left && nq.push(left);
right && nq.push(right);
}
ans.push(s / n);
q.splice(0, q.length, ...nq);
}
return ans;
};
Expand All @@ -299,7 +307,13 @@ var averageOfLevels = function (root) {

<!-- solution:start -->

### 方法二
### 方法二:DFS

我们也可以使用深度优先搜索的方法,来计算每一层的平均值。

具体地,我们定义一个数组 $s$,其中 $s[i]$ 是一个二元组,表示第 $i$ 层的节点值之和以及节点个数。我们对树进行深度优先搜索,对于每一个节点,我们将节点的值加到对应的 $s[i]$ 中,并将节点个数加一。最后,对于每一个 $s[i]$,我们计算平均值,加入答案数组中。

时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点个数。

<!-- tabs:start -->

Expand Down Expand Up @@ -478,8 +492,8 @@ func averageOfLevels(root *TreeNode) []float64 {
* @return {number[]}
*/
var averageOfLevels = function (root) {
let s = [];
let cnt = [];
const s = [];
const cnt = [];
function dfs(root, i) {
if (!root) {
return;
Expand All @@ -495,11 +509,7 @@ var averageOfLevels = function (root) {
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;
return s.map((v, i) => v / cnt[i]);
};
```

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,13 @@ Hence return [3, 14.5, 11].

<!-- solution:start -->

### Solution 1
### Solution 1: BFS

We can use the Breadth-First Search (BFS) method to traverse the nodes of each level and calculate the average value of each level.

Specifically, we define a queue $q$, initially adding the root node to the queue. Each time, we take out all the nodes in the queue, calculate their average value, add it to the answer array, and then add their child nodes to the queue. Repeat this process until the queue is empty.

The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree.

<!-- tabs:start -->

Expand Down Expand Up @@ -151,8 +157,12 @@ public:
root = q.front();
q.pop();
s += root->val;
if (root->left) q.push(root->left);
if (root->right) q.push(root->right);
if (root->left) {
q.push(root->left);
}
if (root->right) {
q.push(root->right);
}
}
ans.push_back(s * 1.0 / n);
}
Expand Down Expand Up @@ -219,29 +229,30 @@ func averageOfLevels(root *TreeNode) []float64 {
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 ans = vec![];
let mut q = VecDeque::new();
q.push_back(Rc::clone(&root.unwrap()));
let mut ans = Vec::new();
if let Some(root_node) = root {
q.push_back(root_node);
}
while !q.is_empty() {
let n = q.len();
let mut sum = 0.0;
let mut s: i64 = 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()));
if let Some(node) = q.pop_front() {
let node_borrow = node.borrow();
s += node_borrow.val as i64;
if let Some(left) = node_borrow.left.clone() {
q.push_back(left);
}
if let Some(right) = node_borrow.right.clone() {
q.push_back(right);
}
}
}
ans.push(sum / (n as f64));
ans.push((s as f64) / (n as f64));
}
ans
}
Expand All @@ -268,18 +279,15 @@ var averageOfLevels = function (root) {
const ans = [];
while (q.length) {
const n = q.length;
const nq = [];
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);
}
for (const { val, left, right } of q) {
s += val;
left && nq.push(left);
right && nq.push(right);
}
ans.push(s / n);
q.splice(0, q.length, ...nq);
}
return ans;
};
Expand All @@ -291,7 +299,13 @@ var averageOfLevels = function (root) {

<!-- solution:start -->

### Solution 2
### Solution 2: DFS

We can also use the Depth-First Search (DFS) method to calculate the average value of each level.

Specifically, we define an array $s$, where $s[i]$ is a tuple representing the sum of node values and the number of nodes at the $i$-th level. We perform a depth-first search on the tree. For each node, we add the node's value to the corresponding $s[i]$ and increment the node count by one. Finally, for each $s[i]$, we calculate the average value and add it to the answer array.

The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree.

<!-- tabs:start -->

Expand Down Expand Up @@ -470,8 +484,8 @@ func averageOfLevels(root *TreeNode) []float64 {
* @return {number[]}
*/
var averageOfLevels = function (root) {
let s = [];
let cnt = [];
const s = [];
const cnt = [];
function dfs(root, i) {
if (!root) {
return;
Expand All @@ -487,11 +501,7 @@ var averageOfLevels = function (root) {
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;
return s.map((v, i) => v / cnt[i]);
};
```

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,12 @@ class Solution {
root = q.front();
q.pop();
s += root->val;
if (root->left) q.push(root->left);
if (root->right) q.push(root->right);
if (root->left) {
q.push(root->left);
}
if (root->right) {
q.push(root->right);
}
}
ans.push_back(s * 1.0 / n);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,15 @@ var averageOfLevels = function (root) {
const ans = [];
while (q.length) {
const n = q.length;
const nq = [];
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);
}
for (const { val, left, right } of q) {
s += val;
left && nq.push(left);
right && nq.push(right);
}
ans.push(s / n);
q.splice(0, q.length, ...nq);
}
return ans;
};
Original file line number Diff line number Diff line change
Expand Up @@ -19,29 +19,30 @@
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 ans = vec![];
let mut q = VecDeque::new();
q.push_back(Rc::clone(&root.unwrap()));
let mut ans = Vec::new();
if let Some(root_node) = root {
q.push_back(root_node);
}
while !q.is_empty() {
let n = q.len();
let mut sum = 0.0;
let mut s: i64 = 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()));
if let Some(node) = q.pop_front() {
let node_borrow = node.borrow();
s += node_borrow.val as i64;
if let Some(left) = node_borrow.left.clone() {
q.push_back(left);
}
if let Some(right) = node_borrow.right.clone() {
q.push_back(right);
}
}
}
ans.push(sum / (n as f64));
ans.push((s as f64) / (n as f64));
}
ans
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
* @return {number[]}
*/
var averageOfLevels = function (root) {
let s = [];
let cnt = [];
const s = [];
const cnt = [];
function dfs(root, i) {
if (!root) {
return;
Expand All @@ -28,9 +28,5 @@ var averageOfLevels = function (root) {
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;
return s.map((v, i) => v / cnt[i]);
};
Loading