From 7f2059f7de0ba0d178e14496fe1a9f30f994dede Mon Sep 17 00:00:00 2001 From: yanglbme Date: Wed, 6 Nov 2024 09:57:08 +0800 Subject: [PATCH] feat: add solutions to lc problem: No.2265 No.2265.Count Nodes Equal to Average of Subtree --- .../README.md | 113 +++++++++++------ .../README_EN.md | 115 ++++++++++++------ .../Solution.cpp | 30 ++--- .../Solution.go | 12 +- .../Solution.java | 9 +- .../Solution.py | 17 +-- .../Solution.ts | 32 +++++ 7 files changed, 217 insertions(+), 111 deletions(-) create mode 100644 solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/Solution.ts diff --git a/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/README.md b/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/README.md index 3474d770ff23b..688c500c92f1c 100644 --- a/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/README.md +++ b/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/README.md @@ -65,31 +65,36 @@ tags: -### 方法一 +### 方法一:DFS + +我们设计一个函数 $\textit{dfs}$,它的作用是计算以当前节点为根的子树的和以及节点个数。 + +函数 $\textit{dfs}$ 的执行过程如下: + +- 如果当前节点为空,返回 $(0, 0)$。 +- 否则,我们递归计算左右子树的和以及节点个数,分别记为 $(\textit{ls}, \textit{ln})$ 和 $(\textit{rs}, \textit{rn})$。那么,以当前节点为根的子树的和 $\textit{s}$ 和节点个数 $\textit{n}$ 分别为 $\textit{ls} + \textit{rs} + \textit{root.val}$ 和 $\textit{ln} + \textit{rn} + 1$。如果 $\textit{s} / \textit{n} = \textit{root.val}$,则说明当前节点满足题目要求,我们将答案 $\textit{ans}$ 自增 $1$。 +- 最后,函数 $\textit{dfs}$ 返回 $\textit{s}$ 和 $\textit{n}$。 + +我们初始化答案 $\textit{ans}$ 为 $0$,然后调用 $\textit{dfs}$ 函数,最后返回答案 $\textit{ans}$。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 表示二叉树的节点个数。 #### Python3 ```python -# 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 averageOfSubtree(self, root: Optional[TreeNode]) -> int: - def dfs(root): - if root is None: + def averageOfSubtree(self, root: TreeNode) -> int: + def dfs(root) -> tuple: + if not root: return 0, 0 ls, ln = dfs(root.left) rs, rn = dfs(root.right) s = ls + rs + root.val n = ln + rn + 1 - if s // n == root.val: - nonlocal ans - ans += 1 + nonlocal ans + ans += int(s // n == root.val) return s, n ans = 0 @@ -119,17 +124,16 @@ class Solution { private int ans; public int averageOfSubtree(TreeNode root) { - ans = 0; dfs(root); return ans; } private int[] dfs(TreeNode root) { if (root == null) { - return new int[] {0, 0}; + return new int[2]; } - int[] l = dfs(root.left); - int[] r = dfs(root.right); + var l = dfs(root.left); + var r = dfs(root.right); int s = l[0] + r[0] + root.val; int n = l[1] + r[1] + 1; if (s / n == root.val) { @@ -156,22 +160,24 @@ class Solution { */ class Solution { public: - int ans; int averageOfSubtree(TreeNode* root) { - ans = 0; - dfs(root); + int ans = 0; + auto dfs = [&](auto&& dfs, TreeNode* root) -> pair { + if (!root) { + return {0, 0}; + } + auto [ls, ln] = dfs(dfs, root->left); + auto [rs, rn] = dfs(dfs, root->right); + int s = ls + rs + root->val; + int n = ln + rn + 1; + if (s / n == root->val) { + ++ans; + } + return {s, n}; + }; + dfs(dfs, root); return ans; } - - vector dfs(TreeNode* root) { - if (!root) return {0, 0}; - auto l = dfs(root->left); - auto r = dfs(root->right); - int s = l[0] + r[0] + root->val; - int n = l[1] + r[1] + 1; - if (s / n == root->val) ++ans; - return {s, n}; - } }; ``` @@ -186,24 +192,59 @@ public: * Right *TreeNode * } */ -func averageOfSubtree(root *TreeNode) int { - ans := 0 - var dfs func(*TreeNode) (int, int) +func averageOfSubtree(root *TreeNode) (ans int) { + var dfs func(root *TreeNode) (int, int) dfs = func(root *TreeNode) (int, int) { if root == nil { return 0, 0 } ls, ln := dfs(root.Left) rs, rn := dfs(root.Right) - s := ls + rs + root.Val - n := ln + rn + 1 + s, n := ls+rs+root.Val, ln+rn+1 if s/n == root.Val { ans++ } return s, n } dfs(root) - return ans + return +} +``` + +#### TypeScript + +```ts +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function averageOfSubtree(root: TreeNode | null): number { + let ans: number = 0; + const dfs = (root: TreeNode | null): [number, number] => { + if (!root) { + return [0, 0]; + } + const [ls, ln] = dfs(root.left); + const [rs, rn] = dfs(root.right); + const s = ls + rs + root.val; + const n = ln + rn + 1; + if (Math.floor(s / n) === root.val) { + ++ans; + } + return [s, n]; + }; + dfs(root); + return ans; } ``` diff --git a/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/README_EN.md b/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/README_EN.md index 9b88f0c4993d9..cb2236a60519a 100644 --- a/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/README_EN.md +++ b/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/README_EN.md @@ -35,7 +35,7 @@ tags:
 Input: root = [4,8,5,0,1,null,6]
 Output: 5
-Explanation: 
+Explanation:
 For the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4.
 For the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5.
 For the node with value 0: The average of its subtree is 0 / 1 = 0.
@@ -65,31 +65,36 @@ For the node with value 6: The average of its subtree is 6 / 1 = 6.
 
 
 
-### Solution 1
+### Solution 1: DFS
+
+We design a function $\textit{dfs}$, which calculates the sum and the number of nodes of the subtree rooted at the current node.
+
+The execution process of the function $\textit{dfs}$ is as follows:
+
+-   If the current node is null, return $(0, 0)$.
+-   Otherwise, we recursively calculate the sum and the number of nodes of the left and right subtrees, denoted as $(\textit{ls}, \textit{ln})$ and $(\textit{rs}, \textit{rn})$, respectively. Then, the sum $\textit{s}$ and the number of nodes $\textit{n}$ of the subtree rooted at the current node are $\textit{ls} + \textit{rs} + \textit{root.val}$ and $\textit{ln} + \textit{rn} + 1$, respectively. If $\textit{s} / \textit{n} = \textit{root.val}$, it means the current node meets the requirement of the problem, and we increment the answer $\textit{ans}$ by $1$.
+-   Finally, the function $\textit{dfs}$ returns $\textit{s}$ and $\textit{n}$.
+
+We initialize the answer $\textit{ans}$ to $0$, then call the $\textit{dfs}$ function, and finally return the answer $\textit{ans}$.
+
+The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ represents the number of nodes in the binary tree.
 
 
 
 #### Python3
 
 ```python
-# 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 averageOfSubtree(self, root: Optional[TreeNode]) -> int:
-        def dfs(root):
-            if root is None:
+    def averageOfSubtree(self, root: TreeNode) -> int:
+        def dfs(root) -> tuple:
+            if not root:
                 return 0, 0
             ls, ln = dfs(root.left)
             rs, rn = dfs(root.right)
             s = ls + rs + root.val
             n = ln + rn + 1
-            if s // n == root.val:
-                nonlocal ans
-                ans += 1
+            nonlocal ans
+            ans += int(s // n == root.val)
             return s, n
 
         ans = 0
@@ -119,17 +124,16 @@ class Solution {
     private int ans;
 
     public int averageOfSubtree(TreeNode root) {
-        ans = 0;
         dfs(root);
         return ans;
     }
 
     private int[] dfs(TreeNode root) {
         if (root == null) {
-            return new int[] {0, 0};
+            return new int[2];
         }
-        int[] l = dfs(root.left);
-        int[] r = dfs(root.right);
+        var l = dfs(root.left);
+        var r = dfs(root.right);
         int s = l[0] + r[0] + root.val;
         int n = l[1] + r[1] + 1;
         if (s / n == root.val) {
@@ -156,22 +160,24 @@ class Solution {
  */
 class Solution {
 public:
-    int ans;
     int averageOfSubtree(TreeNode* root) {
-        ans = 0;
-        dfs(root);
+        int ans = 0;
+        auto dfs = [&](auto&& dfs, TreeNode* root) -> pair {
+            if (!root) {
+                return {0, 0};
+            }
+            auto [ls, ln] = dfs(dfs, root->left);
+            auto [rs, rn] = dfs(dfs, root->right);
+            int s = ls + rs + root->val;
+            int n = ln + rn + 1;
+            if (s / n == root->val) {
+                ++ans;
+            }
+            return {s, n};
+        };
+        dfs(dfs, root);
         return ans;
     }
-
-    vector dfs(TreeNode* root) {
-        if (!root) return {0, 0};
-        auto l = dfs(root->left);
-        auto r = dfs(root->right);
-        int s = l[0] + r[0] + root->val;
-        int n = l[1] + r[1] + 1;
-        if (s / n == root->val) ++ans;
-        return {s, n};
-    }
 };
 ```
 
@@ -186,24 +192,59 @@ public:
  *     Right *TreeNode
  * }
  */
-func averageOfSubtree(root *TreeNode) int {
-	ans := 0
-	var dfs func(*TreeNode) (int, int)
+func averageOfSubtree(root *TreeNode) (ans int) {
+	var dfs func(root *TreeNode) (int, int)
 	dfs = func(root *TreeNode) (int, int) {
 		if root == nil {
 			return 0, 0
 		}
 		ls, ln := dfs(root.Left)
 		rs, rn := dfs(root.Right)
-		s := ls + rs + root.Val
-		n := ln + rn + 1
+		s, n := ls+rs+root.Val, ln+rn+1
 		if s/n == root.Val {
 			ans++
 		}
 		return s, n
 	}
 	dfs(root)
-	return ans
+	return
+}
+```
+
+#### TypeScript
+
+```ts
+/**
+ * Definition for a binary tree node.
+ * class TreeNode {
+ *     val: number
+ *     left: TreeNode | null
+ *     right: TreeNode | null
+ *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
+ *         this.val = (val===undefined ? 0 : val)
+ *         this.left = (left===undefined ? null : left)
+ *         this.right = (right===undefined ? null : right)
+ *     }
+ * }
+ */
+
+function averageOfSubtree(root: TreeNode | null): number {
+    let ans: number = 0;
+    const dfs = (root: TreeNode | null): [number, number] => {
+        if (!root) {
+            return [0, 0];
+        }
+        const [ls, ln] = dfs(root.left);
+        const [rs, rn] = dfs(root.right);
+        const s = ls + rs + root.val;
+        const n = ln + rn + 1;
+        if (Math.floor(s / n) === root.val) {
+            ++ans;
+        }
+        return [s, n];
+    };
+    dfs(root);
+    return ans;
 }
 ```
 
diff --git a/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/Solution.cpp b/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/Solution.cpp
index 6fb5316aa858b..467c4e5344ab2 100644
--- a/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/Solution.cpp	
+++ b/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/Solution.cpp	
@@ -11,20 +11,22 @@
  */
 class Solution {
 public:
-    int ans;
     int averageOfSubtree(TreeNode* root) {
-        ans = 0;
-        dfs(root);
+        int ans = 0;
+        auto dfs = [&](auto&& dfs, TreeNode* root) -> pair {
+            if (!root) {
+                return {0, 0};
+            }
+            auto [ls, ln] = dfs(dfs, root->left);
+            auto [rs, rn] = dfs(dfs, root->right);
+            int s = ls + rs + root->val;
+            int n = ln + rn + 1;
+            if (s / n == root->val) {
+                ++ans;
+            }
+            return {s, n};
+        };
+        dfs(dfs, root);
         return ans;
     }
-
-    vector dfs(TreeNode* root) {
-        if (!root) return {0, 0};
-        auto l = dfs(root->left);
-        auto r = dfs(root->right);
-        int s = l[0] + r[0] + root->val;
-        int n = l[1] + r[1] + 1;
-        if (s / n == root->val) ++ans;
-        return {s, n};
-    }
-};
\ No newline at end of file
+};
diff --git a/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/Solution.go b/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/Solution.go
index 6e133021e7b43..5e8206803ff30 100644
--- a/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/Solution.go	
+++ b/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/Solution.go	
@@ -6,22 +6,20 @@
  *     Right *TreeNode
  * }
  */
-func averageOfSubtree(root *TreeNode) int {
-	ans := 0
-	var dfs func(*TreeNode) (int, int)
+func averageOfSubtree(root *TreeNode) (ans int) {
+	var dfs func(root *TreeNode) (int, int)
 	dfs = func(root *TreeNode) (int, int) {
 		if root == nil {
 			return 0, 0
 		}
 		ls, ln := dfs(root.Left)
 		rs, rn := dfs(root.Right)
-		s := ls + rs + root.Val
-		n := ln + rn + 1
+		s, n := ls+rs+root.Val, ln+rn+1
 		if s/n == root.Val {
 			ans++
 		}
 		return s, n
 	}
 	dfs(root)
-	return ans
-}
\ No newline at end of file
+	return
+}
diff --git a/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/Solution.java b/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/Solution.java
index ab0e38530a398..f94b6001a01b2 100644
--- a/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/Solution.java	
+++ b/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/Solution.java	
@@ -17,17 +17,16 @@ class Solution {
     private int ans;
 
     public int averageOfSubtree(TreeNode root) {
-        ans = 0;
         dfs(root);
         return ans;
     }
 
     private int[] dfs(TreeNode root) {
         if (root == null) {
-            return new int[] {0, 0};
+            return new int[2];
         }
-        int[] l = dfs(root.left);
-        int[] r = dfs(root.right);
+        var l = dfs(root.left);
+        var r = dfs(root.right);
         int s = l[0] + r[0] + root.val;
         int n = l[1] + r[1] + 1;
         if (s / n == root.val) {
@@ -35,4 +34,4 @@ private int[] dfs(TreeNode root) {
         }
         return new int[] {s, n};
     }
-}
\ No newline at end of file
+}
diff --git a/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/Solution.py b/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/Solution.py
index 4145ee6e3ccab..ef18ba16af5c5 100644
--- a/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/Solution.py	
+++ b/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/Solution.py	
@@ -1,21 +1,14 @@
-# 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 averageOfSubtree(self, root: Optional[TreeNode]) -> int:
-        def dfs(root):
-            if root is None:
+    def averageOfSubtree(self, root: TreeNode) -> int:
+        def dfs(root) -> tuple:
+            if not root:
                 return 0, 0
             ls, ln = dfs(root.left)
             rs, rn = dfs(root.right)
             s = ls + rs + root.val
             n = ln + rn + 1
-            if s // n == root.val:
-                nonlocal ans
-                ans += 1
+            nonlocal ans
+            ans += int(s // n == root.val)
             return s, n
 
         ans = 0
diff --git a/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/Solution.ts b/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/Solution.ts
new file mode 100644
index 0000000000000..a826af2cd0188
--- /dev/null
+++ b/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/Solution.ts	
@@ -0,0 +1,32 @@
+/**
+ * Definition for a binary tree node.
+ * class TreeNode {
+ *     val: number
+ *     left: TreeNode | null
+ *     right: TreeNode | null
+ *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
+ *         this.val = (val===undefined ? 0 : val)
+ *         this.left = (left===undefined ? null : left)
+ *         this.right = (right===undefined ? null : right)
+ *     }
+ * }
+ */
+
+function averageOfSubtree(root: TreeNode | null): number {
+    let ans: number = 0;
+    const dfs = (root: TreeNode | null): [number, number] => {
+        if (!root) {
+            return [0, 0];
+        }
+        const [ls, ln] = dfs(root.left);
+        const [rs, rn] = dfs(root.right);
+        const s = ls + rs + root.val;
+        const n = ln + rn + 1;
+        if (Math.floor(s / n) === root.val) {
+            ++ans;
+        }
+        return [s, n];
+    };
+    dfs(root);
+    return ans;
+}