From adc2c20c73cc17f6dd18e6c9d28194d6234b47aa Mon Sep 17 00:00:00 2001 From: yanglbme Date: Tue, 18 Jun 2024 20:32:38 +0800 Subject: [PATCH] feat: update solutions to lc problem: No.637 No.0637.Average of Levels in Binary Tree --- .../README.md | 78 ++++++++++-------- .../README_EN.md | 80 +++++++++++-------- .../Solution.cpp | 8 +- .../Solution.js | 15 ++-- .../Solution.rs | 31 +++---- .../Solution2.js | 10 +-- 6 files changed, 120 insertions(+), 102 deletions(-) diff --git a/solution/0600-0699/0637.Average of Levels in Binary Tree/README.md b/solution/0600-0699/0637.Average of Levels in Binary Tree/README.md index 3709783744053..45dd687b475e8 100644 --- a/solution/0600-0699/0637.Average of Levels in Binary Tree/README.md +++ b/solution/0600-0699/0637.Average of Levels in Binary Tree/README.md @@ -62,6 +62,12 @@ tags: ### 方法一:BFS +我们可以使用广度优先搜索的方法,遍历每一层的节点,计算每一层的平均值。 + +具体地,我们定义一个队列 $q$,初始时将根节点加入队列。每次将队列中的所有节点取出,计算这些节点的平均值,加入答案数组中,并将这些节点的子节点加入队列。重复这一过程,直到队列为空。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点个数。 + #### Python3 @@ -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); } @@ -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>>) -> Vec { - 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 } @@ -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; }; @@ -299,7 +307,13 @@ var averageOfLevels = function (root) { -### 方法二 +### 方法二:DFS + +我们也可以使用深度优先搜索的方法,来计算每一层的平均值。 + +具体地,我们定义一个数组 $s$,其中 $s[i]$ 是一个二元组,表示第 $i$ 层的节点值之和以及节点个数。我们对树进行深度优先搜索,对于每一个节点,我们将节点的值加到对应的 $s[i]$ 中,并将节点个数加一。最后,对于每一个 $s[i]$,我们计算平均值,加入答案数组中。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点个数。 @@ -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; @@ -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]); }; ``` diff --git a/solution/0600-0699/0637.Average of Levels in Binary Tree/README_EN.md b/solution/0600-0699/0637.Average of Levels in Binary Tree/README_EN.md index f86b9ced17929..48727694b31a4 100644 --- a/solution/0600-0699/0637.Average of Levels in Binary Tree/README_EN.md +++ b/solution/0600-0699/0637.Average of Levels in Binary Tree/README_EN.md @@ -52,7 +52,13 @@ Hence return [3, 14.5, 11]. -### 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. @@ -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); } @@ -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>>) -> Vec { - 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 } @@ -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; }; @@ -291,7 +299,13 @@ var averageOfLevels = function (root) { -### 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. @@ -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; @@ -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]); }; ``` diff --git a/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution.cpp b/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution.cpp index bae421864d4dd..cac56d6eebabb 100644 --- a/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution.cpp +++ b/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution.cpp @@ -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); } diff --git a/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution.js b/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution.js index 722ea1c6a93cc..2a443586aeaf4 100644 --- a/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution.js +++ b/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution.js @@ -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; }; diff --git a/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution.rs b/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution.rs index 511514fd613d5..2d48860f9bcc2 100644 --- a/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution.rs +++ b/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution.rs @@ -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>>) -> Vec { - 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 } diff --git a/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution2.js b/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution2.js index e9fdddf35751c..4575498d6ed1a 100644 --- a/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution2.js +++ b/solution/0600-0699/0637.Average of Levels in Binary Tree/Solution2.js @@ -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; @@ -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]); };