From b794dee0360b6bf9b01aad0443084e886d5626d5 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Wed, 24 Jul 2024 19:09:09 +0800 Subject: [PATCH 1/2] feat: update solutions to lc problem: No.0537 No.0537.Complex Number Multiplication --- .../README.md | 62 +++++++++---------- .../README_EN.md | 62 +++++++++---------- .../Solution.cpp | 8 +-- .../Solution.go | 14 ++--- .../Solution.java | 16 ++--- .../Solution.py | 6 +- .../Solution.ts | 12 +--- 7 files changed, 79 insertions(+), 101 deletions(-) diff --git a/solution/0500-0599/0537.Complex Number Multiplication/README.md b/solution/0500-0599/0537.Complex Number Multiplication/README.md index c14888e5658fa..1444dc1d55c38 100644 --- a/solution/0500-0599/0537.Complex Number Multiplication/README.md +++ b/solution/0500-0599/0537.Complex Number Multiplication/README.md @@ -60,7 +60,11 @@ tags: -### 方法一 +### 方法一:模拟 + +我们可以将复数字符串转换成对应的实部 $a$ 和虚部 $b$,然后根据复数乘法的公式 $(a_1 + b_1i) \times (a_2 + b_2i) = (a_1a_2 - b_1b_2) + (a_1b_2 + a_2b_1)i$ 计算出结果。 + +时间复杂度 $O(1)$,空间复杂度 $O(1)$。 @@ -69,9 +73,9 @@ tags: ```python class Solution: def complexNumberMultiply(self, num1: str, num2: str) -> str: - a, b = map(int, num1[:-1].split('+')) - c, d = map(int, num2[:-1].split('+')) - return f'{a * c - b * d}+{a * d + c * b}i' + a1, b1 = map(int, num1[:-1].split("+")) + a2, b2 = map(int, num2[:-1].split("+")) + return f"{a1 * a2 - b1 * b2}+{a1 * b2 + a2 * b1}i" ``` #### Java @@ -79,13 +83,15 @@ class Solution: ```java class Solution { public String complexNumberMultiply(String num1, String num2) { - String[] c1 = num1.split("\\+|i"); - String[] c2 = num2.split("\\+|i"); - int a = Integer.parseInt(c1[0]); - int b = Integer.parseInt(c1[1]); - int c = Integer.parseInt(c2[0]); - int d = Integer.parseInt(c2[1]); - return String.format("%d+%di", a * c - b * d, a * d + c * b); + int[] x = parse(num1); + int[] y = parse(num2); + int a1 = x[0], b1 = x[1], a2 = y[0], b2 = y[1]; + return (a1 * a2 - b1 * b2) + "+" + (a1 * b2 + a2 * b1) + "i"; + } + + private int[] parse(String s) { + var cs = s.substring(0, s.length() - 1).split("\\+"); + return new int[] {Integer.parseInt(cs[0]), Integer.parseInt(cs[1])}; } } ``` @@ -96,10 +102,10 @@ class Solution { class Solution { public: string complexNumberMultiply(string num1, string num2) { - int a, b, c, d; - sscanf(num1.c_str(), "%d+%di", &a, &b); - sscanf(num2.c_str(), "%d+%di", &c, &d); - return string(to_string(a * c - b * d) + "+" + to_string(a * d + c * b) + "i"); + int a1, b1, a2, b2; + sscanf(num1.c_str(), "%d+%di", &a1, &b1); + sscanf(num2.c_str(), "%d+%di", &a2, &b2); + return to_string(a1 * a2 - b1 * b2) + "+" + to_string(a1 * b2 + a2 * b1) + "i"; } }; ``` @@ -107,16 +113,10 @@ public: #### Go ```go -func complexNumberMultiply(num1, num2 string) string { - parse := func(num string) (a, b int) { - i := strings.IndexByte(num, '+') - a, _ = strconv.Atoi(num[:i]) - b, _ = strconv.Atoi(num[i+1 : len(num)-1]) - return - } - a, b := parse(num1) - c, d := parse(num2) - return fmt.Sprintf("%d+%di", a*c-b*d, a*d+b*c) +func complexNumberMultiply(num1 string, num2 string) string { + x, _ := strconv.ParseComplex(num1, 64) + y, _ := strconv.ParseComplex(num2, 64) + return fmt.Sprintf("%d+%di", int(real(x*y)), int(imag(x*y))) } ``` @@ -124,15 +124,9 @@ func complexNumberMultiply(num1, num2 string) string { ```ts function complexNumberMultiply(num1: string, num2: string): string { - let arr1 = num1.split('+'), - arr2 = num2.split('+'); - let r1 = Number(arr1[0]), - r2 = Number(arr2[0]); - let v1 = Number(arr1[1].substring(0, arr1[1].length - 1)), - v2 = Number(arr2[1].substring(0, arr2[1].length - 1)); - let ansR = r1 * r2 - v1 * v2; - let ansV = r1 * v2 + r2 * v1; - return `${ansR}+${ansV}i`; + const [a1, b1] = num1.slice(0, -1).split('+').map(Number); + const [a2, b2] = num2.slice(0, -1).split('+').map(Number); + return `${a1 * a2 - b1 * b2}+${a1 * b2 + a2 * b1}i`; } ``` diff --git a/solution/0500-0599/0537.Complex Number Multiplication/README_EN.md b/solution/0500-0599/0537.Complex Number Multiplication/README_EN.md index 0a60653680fb9..a33b5e90c1c2c 100644 --- a/solution/0500-0599/0537.Complex Number Multiplication/README_EN.md +++ b/solution/0500-0599/0537.Complex Number Multiplication/README_EN.md @@ -58,7 +58,11 @@ tags: -### Solution 1 +### Solution 1: Simulation + +We can convert the complex number string into its real part $a$ and imaginary part $b$, and then use the formula for complex number multiplication $(a_1 + b_1i) \times (a_2 + b_2i) = (a_1a_2 - b_1b_2) + (a_1b_2 + a_2b_1)i$ to calculate the result. + +The time complexity is $O(1)$, and the space complexity is $O(1)$. @@ -67,9 +71,9 @@ tags: ```python class Solution: def complexNumberMultiply(self, num1: str, num2: str) -> str: - a, b = map(int, num1[:-1].split('+')) - c, d = map(int, num2[:-1].split('+')) - return f'{a * c - b * d}+{a * d + c * b}i' + a1, b1 = map(int, num1[:-1].split("+")) + a2, b2 = map(int, num2[:-1].split("+")) + return f"{a1 * a2 - b1 * b2}+{a1 * b2 + a2 * b1}i" ``` #### Java @@ -77,13 +81,15 @@ class Solution: ```java class Solution { public String complexNumberMultiply(String num1, String num2) { - String[] c1 = num1.split("\\+|i"); - String[] c2 = num2.split("\\+|i"); - int a = Integer.parseInt(c1[0]); - int b = Integer.parseInt(c1[1]); - int c = Integer.parseInt(c2[0]); - int d = Integer.parseInt(c2[1]); - return String.format("%d+%di", a * c - b * d, a * d + c * b); + int[] x = parse(num1); + int[] y = parse(num2); + int a1 = x[0], b1 = x[1], a2 = y[0], b2 = y[1]; + return (a1 * a2 - b1 * b2) + "+" + (a1 * b2 + a2 * b1) + "i"; + } + + private int[] parse(String s) { + var cs = s.substring(0, s.length() - 1).split("\\+"); + return new int[] {Integer.parseInt(cs[0]), Integer.parseInt(cs[1])}; } } ``` @@ -94,10 +100,10 @@ class Solution { class Solution { public: string complexNumberMultiply(string num1, string num2) { - int a, b, c, d; - sscanf(num1.c_str(), "%d+%di", &a, &b); - sscanf(num2.c_str(), "%d+%di", &c, &d); - return string(to_string(a * c - b * d) + "+" + to_string(a * d + c * b) + "i"); + int a1, b1, a2, b2; + sscanf(num1.c_str(), "%d+%di", &a1, &b1); + sscanf(num2.c_str(), "%d+%di", &a2, &b2); + return to_string(a1 * a2 - b1 * b2) + "+" + to_string(a1 * b2 + a2 * b1) + "i"; } }; ``` @@ -105,16 +111,10 @@ public: #### Go ```go -func complexNumberMultiply(num1, num2 string) string { - parse := func(num string) (a, b int) { - i := strings.IndexByte(num, '+') - a, _ = strconv.Atoi(num[:i]) - b, _ = strconv.Atoi(num[i+1 : len(num)-1]) - return - } - a, b := parse(num1) - c, d := parse(num2) - return fmt.Sprintf("%d+%di", a*c-b*d, a*d+b*c) +func complexNumberMultiply(num1 string, num2 string) string { + x, _ := strconv.ParseComplex(num1, 64) + y, _ := strconv.ParseComplex(num2, 64) + return fmt.Sprintf("%d+%di", int(real(x*y)), int(imag(x*y))) } ``` @@ -122,15 +122,9 @@ func complexNumberMultiply(num1, num2 string) string { ```ts function complexNumberMultiply(num1: string, num2: string): string { - let arr1 = num1.split('+'), - arr2 = num2.split('+'); - let r1 = Number(arr1[0]), - r2 = Number(arr2[0]); - let v1 = Number(arr1[1].substring(0, arr1[1].length - 1)), - v2 = Number(arr2[1].substring(0, arr2[1].length - 1)); - let ansR = r1 * r2 - v1 * v2; - let ansV = r1 * v2 + r2 * v1; - return `${ansR}+${ansV}i`; + const [a1, b1] = num1.slice(0, -1).split('+').map(Number); + const [a2, b2] = num2.slice(0, -1).split('+').map(Number); + return `${a1 * a2 - b1 * b2}+${a1 * b2 + a2 * b1}i`; } ``` diff --git a/solution/0500-0599/0537.Complex Number Multiplication/Solution.cpp b/solution/0500-0599/0537.Complex Number Multiplication/Solution.cpp index 6d495a4f8cb92..a92eb2ea4aa95 100644 --- a/solution/0500-0599/0537.Complex Number Multiplication/Solution.cpp +++ b/solution/0500-0599/0537.Complex Number Multiplication/Solution.cpp @@ -1,9 +1,9 @@ class Solution { public: string complexNumberMultiply(string num1, string num2) { - int a, b, c, d; - sscanf(num1.c_str(), "%d+%di", &a, &b); - sscanf(num2.c_str(), "%d+%di", &c, &d); - return string(to_string(a * c - b * d) + "+" + to_string(a * d + c * b) + "i"); + int a1, b1, a2, b2; + sscanf(num1.c_str(), "%d+%di", &a1, &b1); + sscanf(num2.c_str(), "%d+%di", &a2, &b2); + return to_string(a1 * a2 - b1 * b2) + "+" + to_string(a1 * b2 + a2 * b1) + "i"; } }; \ No newline at end of file diff --git a/solution/0500-0599/0537.Complex Number Multiplication/Solution.go b/solution/0500-0599/0537.Complex Number Multiplication/Solution.go index 78ff5f4b1484d..70a3125794f4b 100644 --- a/solution/0500-0599/0537.Complex Number Multiplication/Solution.go +++ b/solution/0500-0599/0537.Complex Number Multiplication/Solution.go @@ -1,11 +1,5 @@ -func complexNumberMultiply(num1, num2 string) string { - parse := func(num string) (a, b int) { - i := strings.IndexByte(num, '+') - a, _ = strconv.Atoi(num[:i]) - b, _ = strconv.Atoi(num[i+1 : len(num)-1]) - return - } - a, b := parse(num1) - c, d := parse(num2) - return fmt.Sprintf("%d+%di", a*c-b*d, a*d+b*c) +func complexNumberMultiply(num1 string, num2 string) string { + x, _ := strconv.ParseComplex(num1, 64) + y, _ := strconv.ParseComplex(num2, 64) + return fmt.Sprintf("%d+%di", int(real(x*y)), int(imag(x*y))) } \ No newline at end of file diff --git a/solution/0500-0599/0537.Complex Number Multiplication/Solution.java b/solution/0500-0599/0537.Complex Number Multiplication/Solution.java index 92b77ace32f6f..570b3092f4e1e 100644 --- a/solution/0500-0599/0537.Complex Number Multiplication/Solution.java +++ b/solution/0500-0599/0537.Complex Number Multiplication/Solution.java @@ -1,11 +1,13 @@ class Solution { public String complexNumberMultiply(String num1, String num2) { - String[] c1 = num1.split("\\+|i"); - String[] c2 = num2.split("\\+|i"); - int a = Integer.parseInt(c1[0]); - int b = Integer.parseInt(c1[1]); - int c = Integer.parseInt(c2[0]); - int d = Integer.parseInt(c2[1]); - return String.format("%d+%di", a * c - b * d, a * d + c * b); + int[] x = parse(num1); + int[] y = parse(num2); + int a1 = x[0], b1 = x[1], a2 = y[0], b2 = y[1]; + return (a1 * a2 - b1 * b2) + "+" + (a1 * b2 + a2 * b1) + "i"; + } + + private int[] parse(String s) { + var cs = s.substring(0, s.length() - 1).split("\\+"); + return new int[] {Integer.parseInt(cs[0]), Integer.parseInt(cs[1])}; } } \ No newline at end of file diff --git a/solution/0500-0599/0537.Complex Number Multiplication/Solution.py b/solution/0500-0599/0537.Complex Number Multiplication/Solution.py index 6513c069de99a..8263fe6e32c16 100644 --- a/solution/0500-0599/0537.Complex Number Multiplication/Solution.py +++ b/solution/0500-0599/0537.Complex Number Multiplication/Solution.py @@ -1,5 +1,5 @@ class Solution: def complexNumberMultiply(self, num1: str, num2: str) -> str: - a, b = map(int, num1[:-1].split('+')) - c, d = map(int, num2[:-1].split('+')) - return f'{a * c - b * d}+{a * d + c * b}i' + a1, b1 = map(int, num1[:-1].split("+")) + a2, b2 = map(int, num2[:-1].split("+")) + return f"{a1 * a2 - b1 * b2}+{a1 * b2 + a2 * b1}i" diff --git a/solution/0500-0599/0537.Complex Number Multiplication/Solution.ts b/solution/0500-0599/0537.Complex Number Multiplication/Solution.ts index 0c0589ad52678..1313663055aad 100644 --- a/solution/0500-0599/0537.Complex Number Multiplication/Solution.ts +++ b/solution/0500-0599/0537.Complex Number Multiplication/Solution.ts @@ -1,11 +1,5 @@ function complexNumberMultiply(num1: string, num2: string): string { - let arr1 = num1.split('+'), - arr2 = num2.split('+'); - let r1 = Number(arr1[0]), - r2 = Number(arr2[0]); - let v1 = Number(arr1[1].substring(0, arr1[1].length - 1)), - v2 = Number(arr2[1].substring(0, arr2[1].length - 1)); - let ansR = r1 * r2 - v1 * v2; - let ansV = r1 * v2 + r2 * v1; - return `${ansR}+${ansV}i`; + const [a1, b1] = num1.slice(0, -1).split('+').map(Number); + const [a2, b2] = num2.slice(0, -1).split('+').map(Number); + return `${a1 * a2 - b1 * b2}+${a1 * b2 + a2 * b1}i`; } From 28afabd1c1c7f27a5cc5094ab09fa119aa45bc16 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Wed, 24 Jul 2024 19:30:26 +0800 Subject: [PATCH 2/2] feat: add solutions to lc problems: No.0530,0783 * No.0530.Minimum Absolute Difference in BST * No.0783.Minimum Distance Between BST Nodes --- .../README.md | 187 +++++++++-------- .../README_EN.md | 189 ++++++++++-------- .../Solution.cpp | 26 ++- .../Solution.go | 15 +- .../Solution.java | 12 +- .../Solution.js | 26 +++ .../Solution.py | 13 +- .../Solution.rs | 32 ++- .../Solution.ts | 26 +-- .../README.md | 163 +++++++++++---- .../README_EN.md | 165 +++++++++++---- .../Solution.cpp | 26 ++- .../Solution.go | 15 +- .../Solution.java | 12 +- .../Solution.js | 19 +- .../Solution.py | 11 +- .../Solution.rs | 40 ++++ .../Solution.ts | 28 +++ 18 files changed, 643 insertions(+), 362 deletions(-) create mode 100644 solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.js create mode 100644 solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.rs create mode 100644 solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.ts diff --git a/solution/0500-0599/0530.Minimum Absolute Difference in BST/README.md b/solution/0500-0599/0530.Minimum Absolute Difference in BST/README.md index b5759e2fcdfaa..1c4d16502b73e 100644 --- a/solution/0500-0599/0530.Minimum Absolute Difference in BST/README.md +++ b/solution/0500-0599/0530.Minimum Absolute Difference in BST/README.md @@ -61,7 +61,11 @@ tags: ### 方法一:中序遍历 -中序遍历二叉搜索树,获取当前节点与上个节点差值的最小值即可。 +题目需要我们求任意两个节点值之间的最小差值,而二叉搜索树的中序遍历是一个递增序列,因此我们只需要求中序遍历中相邻两个节点值之间的最小差值即可。 + +我们可以使用递归的方法来实现中序遍历,过程中用一个变量 $\textit{pre}$ 来保存前一个节点的值,这样我们就可以在遍历的过程中求出相邻两个节点值之间的最小差值。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉搜索树的节点个数。 @@ -75,17 +79,18 @@ tags: # self.left = left # self.right = right class Solution: - def getMinimumDifference(self, root: TreeNode) -> int: - def dfs(root): + def getMinimumDifference(self, root: Optional[TreeNode]) -> int: + def dfs(root: Optional[TreeNode]): if root is None: return dfs(root.left) - nonlocal ans, prev - ans = min(ans, abs(prev - root.val)) - prev = root.val + nonlocal pre, ans + ans = min(ans, root.val - pre) + pre = root.val dfs(root.right) - ans = prev = inf + pre = -inf + ans = inf dfs(root) return ans ``` @@ -109,13 +114,11 @@ class Solution: * } */ class Solution { - private int ans; - private int prev; - private int inf = Integer.MAX_VALUE; + private final int inf = 1 << 30; + private int ans = inf; + private int pre = -inf; public int getMinimumDifference(TreeNode root) { - ans = inf; - prev = inf; dfs(root); return ans; } @@ -125,8 +128,8 @@ class Solution { return; } dfs(root.left); - ans = Math.min(ans, Math.abs(root.val - prev)); - prev = root.val; + ans = Math.min(ans, root.val - pre); + pre = root.val; dfs(root.right); } } @@ -148,23 +151,21 @@ class Solution { */ class Solution { public: - const int inf = INT_MAX; - int ans; - int prev; - int getMinimumDifference(TreeNode* root) { - ans = inf, prev = inf; - dfs(root); + const int inf = 1 << 30; + int ans = inf, pre = -inf; + auto dfs = [&](auto&& dfs, TreeNode* root) -> void { + if (!root) { + return; + } + dfs(dfs, root->left); + ans = min(ans, root->val - pre); + pre = root->val; + dfs(dfs, root->right); + }; + dfs(dfs, root); return ans; } - - void dfs(TreeNode* root) { - if (!root) return; - dfs(root->left); - ans = min(ans, abs(prev - root->val)); - prev = root->val; - dfs(root->right); - } }; ``` @@ -180,27 +181,53 @@ public: * } */ func getMinimumDifference(root *TreeNode) int { - inf := 0x3f3f3f3f - ans, prev := inf, inf + const inf int = 1 << 30 + ans, pre := inf, -inf var dfs func(*TreeNode) dfs = func(root *TreeNode) { if root == nil { return } dfs(root.Left) - ans = min(ans, abs(prev-root.Val)) - prev = root.Val + ans = min(ans, root.Val-pre) + pre = root.Val dfs(root.Right) } dfs(root) return ans } +``` -func abs(x int) int { - if x < 0 { - return -x - } - return x +#### 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 getMinimumDifference(root: TreeNode | null): number { + let [ans, pre] = [Infinity, -Infinity]; + const dfs = (root: TreeNode | null) => { + if (!root) { + return; + } + dfs(root.left); + ans = Math.min(ans, root.val - pre); + pre = root.val; + dfs(root.right); + }; + dfs(root); + return ans; } ``` @@ -225,69 +252,59 @@ func abs(x int) int { // } // } // } -use std::cell::RefCell; use std::rc::Rc; +use std::cell::RefCell; impl Solution { - #[allow(dead_code)] pub fn get_minimum_difference(root: Option>>) -> i32 { - let mut ret = i32::MAX; - let mut prev = i32::MAX; - Self::traverse(root, &mut prev, &mut ret); - ret - } - - #[allow(dead_code)] - fn traverse(root: Option>>, prev: &mut i32, ans: &mut i32) { - let left = root.as_ref().unwrap().borrow().left.clone(); - let right = root.as_ref().unwrap().borrow().right.clone(); - let val = root.as_ref().unwrap().borrow().val; - if !left.is_none() { - Self::traverse(left.clone(), prev, ans); - } - *ans = std::cmp::min(*ans, (*prev - val).abs()); - *prev = val; - if !right.is_none() { - Self::traverse(right.clone(), prev, ans); + const inf: i32 = 1 << 30; + let mut ans = inf; + let mut pre = -inf; + + fn dfs(node: Option>>, ans: &mut i32, pre: &mut i32) { + if let Some(n) = node { + let n = n.borrow(); + dfs(n.left.clone(), ans, pre); + *ans = (*ans).min(n.val - *pre); + *pre = n.val; + dfs(n.right.clone(), ans, pre); + } } + + dfs(root, &mut ans, &mut pre); + ans } } ``` -#### TypeScript +#### JavaScript -```ts +```js /** * 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 TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) * } */ -function getMinimumDifference(root: TreeNode | null): number { - if (!root) return 0; - - let prev = Number.MIN_SAFE_INTEGER; - let min = Number.MAX_SAFE_INTEGER; - - const dfs = (node: TreeNode | null) => { - if (!node) return; - - dfs(node.left); - min = Math.min(min, node.val - prev); - prev = node.val; - dfs(node.right); +/** + * @param {TreeNode} root + * @return {number} + */ +var getMinimumDifference = function (root) { + let [ans, pre] = [Infinity, -Infinity]; + const dfs = root => { + if (!root) { + return; + } + dfs(root.left); + ans = Math.min(ans, root.val - pre); + pre = root.val; + dfs(root.right); }; - dfs(root); - - return min; -} + return ans; +}; ``` diff --git a/solution/0500-0599/0530.Minimum Absolute Difference in BST/README_EN.md b/solution/0500-0599/0530.Minimum Absolute Difference in BST/README_EN.md index c844437fd016a..ee82a161f1f67 100644 --- a/solution/0500-0599/0530.Minimum Absolute Difference in BST/README_EN.md +++ b/solution/0500-0599/0530.Minimum Absolute Difference in BST/README_EN.md @@ -54,7 +54,13 @@ tags: -### Solution 1 +### Solution 1: Inorder Traversal + +The problem requires us to find the minimum difference between the values of any two nodes. Since the inorder traversal of a binary search tree is an increasing sequence, we only need to find the minimum difference between the values of two adjacent nodes in the inorder traversal. + +We can use a recursive method to implement the inorder traversal. During the process, we use a variable $\textit{pre}$ to save the value of the previous node. This way, we can calculate the minimum difference between the values of two adjacent nodes during the traversal. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary search tree. @@ -68,17 +74,18 @@ tags: # self.left = left # self.right = right class Solution: - def getMinimumDifference(self, root: TreeNode) -> int: - def dfs(root): + def getMinimumDifference(self, root: Optional[TreeNode]) -> int: + def dfs(root: Optional[TreeNode]): if root is None: return dfs(root.left) - nonlocal ans, prev - ans = min(ans, abs(prev - root.val)) - prev = root.val + nonlocal pre, ans + ans = min(ans, root.val - pre) + pre = root.val dfs(root.right) - ans = prev = inf + pre = -inf + ans = inf dfs(root) return ans ``` @@ -102,13 +109,11 @@ class Solution: * } */ class Solution { - private int ans; - private int prev; - private int inf = Integer.MAX_VALUE; + private final int inf = 1 << 30; + private int ans = inf; + private int pre = -inf; public int getMinimumDifference(TreeNode root) { - ans = inf; - prev = inf; dfs(root); return ans; } @@ -118,8 +123,8 @@ class Solution { return; } dfs(root.left); - ans = Math.min(ans, Math.abs(root.val - prev)); - prev = root.val; + ans = Math.min(ans, root.val - pre); + pre = root.val; dfs(root.right); } } @@ -141,23 +146,21 @@ class Solution { */ class Solution { public: - const int inf = INT_MAX; - int ans; - int prev; - int getMinimumDifference(TreeNode* root) { - ans = inf, prev = inf; - dfs(root); + const int inf = 1 << 30; + int ans = inf, pre = -inf; + auto dfs = [&](auto&& dfs, TreeNode* root) -> void { + if (!root) { + return; + } + dfs(dfs, root->left); + ans = min(ans, root->val - pre); + pre = root->val; + dfs(dfs, root->right); + }; + dfs(dfs, root); return ans; } - - void dfs(TreeNode* root) { - if (!root) return; - dfs(root->left); - ans = min(ans, abs(prev - root->val)); - prev = root->val; - dfs(root->right); - } }; ``` @@ -173,27 +176,53 @@ public: * } */ func getMinimumDifference(root *TreeNode) int { - inf := 0x3f3f3f3f - ans, prev := inf, inf + const inf int = 1 << 30 + ans, pre := inf, -inf var dfs func(*TreeNode) dfs = func(root *TreeNode) { if root == nil { return } dfs(root.Left) - ans = min(ans, abs(prev-root.Val)) - prev = root.Val + ans = min(ans, root.Val-pre) + pre = root.Val dfs(root.Right) } dfs(root) return ans } +``` -func abs(x int) int { - if x < 0 { - return -x - } - return x +#### 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 getMinimumDifference(root: TreeNode | null): number { + let [ans, pre] = [Infinity, -Infinity]; + const dfs = (root: TreeNode | null) => { + if (!root) { + return; + } + dfs(root.left); + ans = Math.min(ans, root.val - pre); + pre = root.val; + dfs(root.right); + }; + dfs(root); + return ans; } ``` @@ -218,69 +247,59 @@ func abs(x int) int { // } // } // } -use std::cell::RefCell; use std::rc::Rc; +use std::cell::RefCell; impl Solution { - #[allow(dead_code)] pub fn get_minimum_difference(root: Option>>) -> i32 { - let mut ret = i32::MAX; - let mut prev = i32::MAX; - Self::traverse(root, &mut prev, &mut ret); - ret - } - - #[allow(dead_code)] - fn traverse(root: Option>>, prev: &mut i32, ans: &mut i32) { - let left = root.as_ref().unwrap().borrow().left.clone(); - let right = root.as_ref().unwrap().borrow().right.clone(); - let val = root.as_ref().unwrap().borrow().val; - if !left.is_none() { - Self::traverse(left.clone(), prev, ans); - } - *ans = std::cmp::min(*ans, (*prev - val).abs()); - *prev = val; - if !right.is_none() { - Self::traverse(right.clone(), prev, ans); + const inf: i32 = 1 << 30; + let mut ans = inf; + let mut pre = -inf; + + fn dfs(node: Option>>, ans: &mut i32, pre: &mut i32) { + if let Some(n) = node { + let n = n.borrow(); + dfs(n.left.clone(), ans, pre); + *ans = (*ans).min(n.val - *pre); + *pre = n.val; + dfs(n.right.clone(), ans, pre); + } } + + dfs(root, &mut ans, &mut pre); + ans } } ``` -#### TypeScript +#### JavaScript -```ts +```js /** * 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 TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) * } */ -function getMinimumDifference(root: TreeNode | null): number { - if (!root) return 0; - - let prev = Number.MIN_SAFE_INTEGER; - let min = Number.MAX_SAFE_INTEGER; - - const dfs = (node: TreeNode | null) => { - if (!node) return; - - dfs(node.left); - min = Math.min(min, node.val - prev); - prev = node.val; - dfs(node.right); +/** + * @param {TreeNode} root + * @return {number} + */ +var getMinimumDifference = function (root) { + let [ans, pre] = [Infinity, -Infinity]; + const dfs = root => { + if (!root) { + return; + } + dfs(root.left); + ans = Math.min(ans, root.val - pre); + pre = root.val; + dfs(root.right); }; - dfs(root); - - return min; -} + return ans; +}; ``` diff --git a/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.cpp b/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.cpp index 578e0615cd4b2..aefc98065b5ba 100644 --- a/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.cpp +++ b/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.cpp @@ -11,21 +11,19 @@ */ class Solution { public: - const int inf = INT_MAX; - int ans; - int prev; - int getMinimumDifference(TreeNode* root) { - ans = inf, prev = inf; - dfs(root); + const int inf = 1 << 30; + int ans = inf, pre = -inf; + auto dfs = [&](auto&& dfs, TreeNode* root) -> void { + if (!root) { + return; + } + dfs(dfs, root->left); + ans = min(ans, root->val - pre); + pre = root->val; + dfs(dfs, root->right); + }; + dfs(dfs, root); return ans; } - - void dfs(TreeNode* root) { - if (!root) return; - dfs(root->left); - ans = min(ans, abs(prev - root->val)); - prev = root->val; - dfs(root->right); - } }; \ No newline at end of file diff --git a/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.go b/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.go index 7d7440f7d846b..f007348398b7b 100644 --- a/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.go +++ b/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.go @@ -7,25 +7,18 @@ * } */ func getMinimumDifference(root *TreeNode) int { - inf := 0x3f3f3f3f - ans, prev := inf, inf + const inf int = 1 << 30 + ans, pre := inf, -inf var dfs func(*TreeNode) dfs = func(root *TreeNode) { if root == nil { return } dfs(root.Left) - ans = min(ans, abs(prev-root.Val)) - prev = root.Val + ans = min(ans, root.Val-pre) + pre = root.Val dfs(root.Right) } dfs(root) return ans -} - -func abs(x int) int { - if x < 0 { - return -x - } - return x } \ No newline at end of file diff --git a/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.java b/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.java index 190ac5efddae7..3b0b489278000 100644 --- a/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.java +++ b/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.java @@ -14,13 +14,11 @@ * } */ class Solution { - private int ans; - private int prev; - private int inf = Integer.MAX_VALUE; + private final int inf = 1 << 30; + private int ans = inf; + private int pre = -inf; public int getMinimumDifference(TreeNode root) { - ans = inf; - prev = inf; dfs(root); return ans; } @@ -30,8 +28,8 @@ private void dfs(TreeNode root) { return; } dfs(root.left); - ans = Math.min(ans, Math.abs(root.val - prev)); - prev = root.val; + ans = Math.min(ans, root.val - pre); + pre = root.val; dfs(root.right); } } \ No newline at end of file diff --git a/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.js b/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.js new file mode 100644 index 0000000000000..ff16b30be4a69 --- /dev/null +++ b/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.js @@ -0,0 +1,26 @@ +/** + * 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 getMinimumDifference = function (root) { + let [ans, pre] = [Infinity, -Infinity]; + const dfs = root => { + if (!root) { + return; + } + dfs(root.left); + ans = Math.min(ans, root.val - pre); + pre = root.val; + dfs(root.right); + }; + dfs(root); + return ans; +}; diff --git a/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.py b/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.py index eda3e769918d4..7862484bd303c 100644 --- a/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.py +++ b/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.py @@ -5,16 +5,17 @@ # self.left = left # self.right = right class Solution: - def getMinimumDifference(self, root: TreeNode) -> int: - def dfs(root): + def getMinimumDifference(self, root: Optional[TreeNode]) -> int: + def dfs(root: Optional[TreeNode]): if root is None: return dfs(root.left) - nonlocal ans, prev - ans = min(ans, abs(prev - root.val)) - prev = root.val + nonlocal pre, ans + ans = min(ans, root.val - pre) + pre = root.val dfs(root.right) - ans = prev = inf + pre = -inf + ans = inf dfs(root) return ans diff --git a/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.rs b/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.rs index cf5396d9060ed..1deee6d8efca7 100644 --- a/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.rs +++ b/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.rs @@ -19,26 +19,22 @@ use std::cell::RefCell; use std::rc::Rc; impl Solution { - #[allow(dead_code)] pub fn get_minimum_difference(root: Option>>) -> i32 { - let mut ret = i32::MAX; - let mut prev = i32::MAX; - Self::traverse(root, &mut prev, &mut ret); - ret - } + const inf: i32 = 1 << 30; + let mut ans = inf; + let mut pre = -inf; - #[allow(dead_code)] - fn traverse(root: Option>>, prev: &mut i32, ans: &mut i32) { - let left = root.as_ref().unwrap().borrow().left.clone(); - let right = root.as_ref().unwrap().borrow().right.clone(); - let val = root.as_ref().unwrap().borrow().val; - if !left.is_none() { - Self::traverse(left.clone(), prev, ans); - } - *ans = std::cmp::min(*ans, (*prev - val).abs()); - *prev = val; - if !right.is_none() { - Self::traverse(right.clone(), prev, ans); + fn dfs(node: Option>>, ans: &mut i32, pre: &mut i32) { + if let Some(n) = node { + let n = n.borrow(); + dfs(n.left.clone(), ans, pre); + *ans = (*ans).min(n.val - *pre); + *pre = n.val; + dfs(n.right.clone(), ans, pre); + } } + + dfs(root, &mut ans, &mut pre); + ans } } diff --git a/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.ts b/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.ts index 61275353165c6..c4d98f25156f3 100644 --- a/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.ts +++ b/solution/0500-0599/0530.Minimum Absolute Difference in BST/Solution.ts @@ -11,22 +11,18 @@ * } * } */ -function getMinimumDifference(root: TreeNode | null): number { - if (!root) return 0; - - let prev = Number.MIN_SAFE_INTEGER; - let min = Number.MAX_SAFE_INTEGER; - - const dfs = (node: TreeNode | null) => { - if (!node) return; - dfs(node.left); - min = Math.min(min, node.val - prev); - prev = node.val; - dfs(node.right); +function getMinimumDifference(root: TreeNode | null): number { + let [ans, pre] = [Infinity, -Infinity]; + const dfs = (root: TreeNode | null) => { + if (!root) { + return; + } + dfs(root.left); + ans = Math.min(ans, root.val - pre); + pre = root.val; + dfs(root.right); }; - dfs(root); - - return min; + return ans; } diff --git a/solution/0700-0799/0783.Minimum Distance Between BST Nodes/README.md b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/README.md index 10c0cb8778cbc..bcb964c9355fa 100644 --- a/solution/0700-0799/0783.Minimum Distance Between BST Nodes/README.md +++ b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/README.md @@ -65,7 +65,11 @@ tags: ### 方法一:中序遍历 -中序遍历二叉搜索树,获取当前节点与上个节点差值的最小值即可。 +题目需要我们求任意两个节点值之间的最小差值,而二叉搜索树的中序遍历是一个递增序列,因此我们只需要求中序遍历中相邻两个节点值之间的最小差值即可。 + +我们可以使用递归的方法来实现中序遍历,过程中用一个变量 $\textit{pre}$ 来保存前一个节点的值,这样我们就可以在遍历的过程中求出相邻两个节点值之间的最小差值。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉搜索树的节点个数。 @@ -80,16 +84,17 @@ tags: # self.right = right class Solution: def minDiffInBST(self, root: Optional[TreeNode]) -> int: - def dfs(root): + def dfs(root: Optional[TreeNode]): if root is None: return dfs(root.left) - nonlocal ans, prev - ans = min(ans, abs(prev - root.val)) - prev = root.val + nonlocal pre, ans + ans = min(ans, root.val - pre) + pre = root.val dfs(root.right) - ans = prev = inf + pre = -inf + ans = inf dfs(root) return ans ``` @@ -113,13 +118,11 @@ class Solution: * } */ class Solution { - private int ans; - private int prev; - private int inf = Integer.MAX_VALUE; + private final int inf = 1 << 30; + private int ans = inf; + private int pre = -inf; public int minDiffInBST(TreeNode root) { - ans = inf; - prev = inf; dfs(root); return ans; } @@ -129,8 +132,8 @@ class Solution { return; } dfs(root.left); - ans = Math.min(ans, Math.abs(root.val - prev)); - prev = root.val; + ans = Math.min(ans, root.val - pre); + pre = root.val; dfs(root.right); } } @@ -152,23 +155,21 @@ class Solution { */ class Solution { public: - const int inf = INT_MAX; - int ans; - int prev; - int minDiffInBST(TreeNode* root) { - ans = inf, prev = inf; - dfs(root); + const int inf = 1 << 30; + int ans = inf, pre = -inf; + auto dfs = [&](auto&& dfs, TreeNode* root) -> void { + if (!root) { + return; + } + dfs(dfs, root->left); + ans = min(ans, root->val - pre); + pre = root->val; + dfs(dfs, root->right); + }; + dfs(dfs, root); return ans; } - - void dfs(TreeNode* root) { - if (!root) return; - dfs(root->left); - ans = min(ans, abs(prev - root->val)); - prev = root->val; - dfs(root->right); - } }; ``` @@ -184,43 +185,125 @@ public: * } */ func minDiffInBST(root *TreeNode) int { - inf := 0x3f3f3f3f - ans, prev := inf, inf + const inf int = 1 << 30 + ans, pre := inf, -inf var dfs func(*TreeNode) dfs = func(root *TreeNode) { if root == nil { return } dfs(root.Left) - ans = min(ans, abs(prev-root.Val)) - prev = root.Val + ans = min(ans, root.Val-pre) + pre = root.Val dfs(root.Right) } dfs(root) return ans } +``` -func abs(x int) int { - if x < 0 { - return -x - } - return x +#### 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 minDiffInBST(root: TreeNode | null): number { + let [ans, pre] = [Infinity, -Infinity]; + const dfs = (root: TreeNode | null) => { + if (!root) { + return; + } + dfs(root.left); + ans = Math.min(ans, root.val - pre); + pre = root.val; + dfs(root.right); + }; + dfs(root); + return ans; +} +``` + +#### Rust + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::cell::RefCell; +use std::rc::Rc; +impl Solution { + pub fn min_diff_in_bst(root: Option>>) -> i32 { + const inf: i32 = 1 << 30; + let mut ans = inf; + let mut pre = -inf; + + fn dfs(node: Option>>, ans: &mut i32, pre: &mut i32) { + if let Some(n) = node { + let n = n.borrow(); + dfs(n.left.clone(), ans, pre); + *ans = (*ans).min(n.val - *pre); + *pre = n.val; + dfs(n.right.clone(), ans, pre); + } + } + + dfs(root, &mut ans, &mut pre); + ans + } } ``` #### JavaScript ```js +/** + * 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 minDiffInBST = function (root) { - let ans = Number.MAX_SAFE_INTEGER, - prev = Number.MAX_SAFE_INTEGER; + let [ans, pre] = [Infinity, -Infinity]; const dfs = root => { if (!root) { return; } dfs(root.left); - ans = Math.min(ans, Math.abs(root.val - prev)); - prev = root.val; + ans = Math.min(ans, root.val - pre); + pre = root.val; dfs(root.right); }; dfs(root); diff --git a/solution/0700-0799/0783.Minimum Distance Between BST Nodes/README_EN.md b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/README_EN.md index 68cccd842c61b..4c207c9590d97 100644 --- a/solution/0700-0799/0783.Minimum Distance Between BST Nodes/README_EN.md +++ b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/README_EN.md @@ -54,7 +54,13 @@ tags: -### Solution 1 +### Solution 1: Inorder Traversal + +The problem requires us to find the minimum difference between the values of any two nodes. Since the inorder traversal of a binary search tree is an increasing sequence, we only need to find the minimum difference between the values of two adjacent nodes in the inorder traversal. + +We can use a recursive method to implement the inorder traversal. During the process, we use a variable $\textit{pre}$ to save the value of the previous node. This way, we can calculate the minimum difference between the values of two adjacent nodes during the traversal. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary search tree. @@ -69,16 +75,17 @@ tags: # self.right = right class Solution: def minDiffInBST(self, root: Optional[TreeNode]) -> int: - def dfs(root): + def dfs(root: Optional[TreeNode]): if root is None: return dfs(root.left) - nonlocal ans, prev - ans = min(ans, abs(prev - root.val)) - prev = root.val + nonlocal pre, ans + ans = min(ans, root.val - pre) + pre = root.val dfs(root.right) - ans = prev = inf + pre = -inf + ans = inf dfs(root) return ans ``` @@ -102,13 +109,11 @@ class Solution: * } */ class Solution { - private int ans; - private int prev; - private int inf = Integer.MAX_VALUE; + private final int inf = 1 << 30; + private int ans = inf; + private int pre = -inf; public int minDiffInBST(TreeNode root) { - ans = inf; - prev = inf; dfs(root); return ans; } @@ -118,8 +123,8 @@ class Solution { return; } dfs(root.left); - ans = Math.min(ans, Math.abs(root.val - prev)); - prev = root.val; + ans = Math.min(ans, root.val - pre); + pre = root.val; dfs(root.right); } } @@ -141,23 +146,21 @@ class Solution { */ class Solution { public: - const int inf = INT_MAX; - int ans; - int prev; - int minDiffInBST(TreeNode* root) { - ans = inf, prev = inf; - dfs(root); + const int inf = 1 << 30; + int ans = inf, pre = -inf; + auto dfs = [&](auto&& dfs, TreeNode* root) -> void { + if (!root) { + return; + } + dfs(dfs, root->left); + ans = min(ans, root->val - pre); + pre = root->val; + dfs(dfs, root->right); + }; + dfs(dfs, root); return ans; } - - void dfs(TreeNode* root) { - if (!root) return; - dfs(root->left); - ans = min(ans, abs(prev - root->val)); - prev = root->val; - dfs(root->right); - } }; ``` @@ -173,43 +176,125 @@ public: * } */ func minDiffInBST(root *TreeNode) int { - inf := 0x3f3f3f3f - ans, prev := inf, inf + const inf int = 1 << 30 + ans, pre := inf, -inf var dfs func(*TreeNode) dfs = func(root *TreeNode) { if root == nil { return } dfs(root.Left) - ans = min(ans, abs(prev-root.Val)) - prev = root.Val + ans = min(ans, root.Val-pre) + pre = root.Val dfs(root.Right) } dfs(root) return ans } +``` -func abs(x int) int { - if x < 0 { - return -x - } - return x +#### 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 minDiffInBST(root: TreeNode | null): number { + let [ans, pre] = [Infinity, -Infinity]; + const dfs = (root: TreeNode | null) => { + if (!root) { + return; + } + dfs(root.left); + ans = Math.min(ans, root.val - pre); + pre = root.val; + dfs(root.right); + }; + dfs(root); + return ans; +} +``` + +#### Rust + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::cell::RefCell; +use std::rc::Rc; +impl Solution { + pub fn min_diff_in_bst(root: Option>>) -> i32 { + const inf: i32 = 1 << 30; + let mut ans = inf; + let mut pre = -inf; + + fn dfs(node: Option>>, ans: &mut i32, pre: &mut i32) { + if let Some(n) = node { + let n = n.borrow(); + dfs(n.left.clone(), ans, pre); + *ans = (*ans).min(n.val - *pre); + *pre = n.val; + dfs(n.right.clone(), ans, pre); + } + } + + dfs(root, &mut ans, &mut pre); + ans + } } ``` #### JavaScript ```js +/** + * 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 minDiffInBST = function (root) { - let ans = Number.MAX_SAFE_INTEGER, - prev = Number.MAX_SAFE_INTEGER; + let [ans, pre] = [Infinity, -Infinity]; const dfs = root => { if (!root) { return; } dfs(root.left); - ans = Math.min(ans, Math.abs(root.val - prev)); - prev = root.val; + ans = Math.min(ans, root.val - pre); + pre = root.val; dfs(root.right); }; dfs(root); diff --git a/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.cpp b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.cpp index 64c21f404198c..9857cb328afcc 100644 --- a/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.cpp +++ b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.cpp @@ -11,21 +11,19 @@ */ class Solution { public: - const int inf = INT_MAX; - int ans; - int prev; - int minDiffInBST(TreeNode* root) { - ans = inf, prev = inf; - dfs(root); + const int inf = 1 << 30; + int ans = inf, pre = -inf; + auto dfs = [&](auto&& dfs, TreeNode* root) -> void { + if (!root) { + return; + } + dfs(dfs, root->left); + ans = min(ans, root->val - pre); + pre = root->val; + dfs(dfs, root->right); + }; + dfs(dfs, root); return ans; } - - void dfs(TreeNode* root) { - if (!root) return; - dfs(root->left); - ans = min(ans, abs(prev - root->val)); - prev = root->val; - dfs(root->right); - } }; \ No newline at end of file diff --git a/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.go b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.go index 9182cbbff1ba4..194ba212909ac 100644 --- a/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.go +++ b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.go @@ -7,25 +7,18 @@ * } */ func minDiffInBST(root *TreeNode) int { - inf := 0x3f3f3f3f - ans, prev := inf, inf + const inf int = 1 << 30 + ans, pre := inf, -inf var dfs func(*TreeNode) dfs = func(root *TreeNode) { if root == nil { return } dfs(root.Left) - ans = min(ans, abs(prev-root.Val)) - prev = root.Val + ans = min(ans, root.Val-pre) + pre = root.Val dfs(root.Right) } dfs(root) return ans -} - -func abs(x int) int { - if x < 0 { - return -x - } - return x } \ No newline at end of file diff --git a/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.java b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.java index 833beeb80409c..5eb284d83307f 100644 --- a/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.java +++ b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.java @@ -14,13 +14,11 @@ * } */ class Solution { - private int ans; - private int prev; - private int inf = Integer.MAX_VALUE; + private final int inf = 1 << 30; + private int ans = inf; + private int pre = -inf; public int minDiffInBST(TreeNode root) { - ans = inf; - prev = inf; dfs(root); return ans; } @@ -30,8 +28,8 @@ private void dfs(TreeNode root) { return; } dfs(root.left); - ans = Math.min(ans, Math.abs(root.val - prev)); - prev = root.val; + ans = Math.min(ans, root.val - pre); + pre = root.val; dfs(root.right); } } \ No newline at end of file diff --git a/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.js b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.js index bd65098d3ae9c..af7b45c90f942 100644 --- a/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.js +++ b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.js @@ -1,13 +1,24 @@ +/** + * 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 minDiffInBST = function (root) { - let ans = Number.MAX_SAFE_INTEGER, - prev = Number.MAX_SAFE_INTEGER; + let [ans, pre] = [Infinity, -Infinity]; const dfs = root => { if (!root) { return; } dfs(root.left); - ans = Math.min(ans, Math.abs(root.val - prev)); - prev = root.val; + ans = Math.min(ans, root.val - pre); + pre = root.val; dfs(root.right); }; dfs(root); diff --git a/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.py b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.py index 3c538a0621ab3..16dae22a1c60a 100644 --- a/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.py +++ b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.py @@ -6,15 +6,16 @@ # self.right = right class Solution: def minDiffInBST(self, root: Optional[TreeNode]) -> int: - def dfs(root): + def dfs(root: Optional[TreeNode]): if root is None: return dfs(root.left) - nonlocal ans, prev - ans = min(ans, abs(prev - root.val)) - prev = root.val + nonlocal pre, ans + ans = min(ans, root.val - pre) + pre = root.val dfs(root.right) - ans = prev = inf + pre = -inf + ans = inf dfs(root) return ans diff --git a/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.rs b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.rs new file mode 100644 index 0000000000000..6919097830763 --- /dev/null +++ b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.rs @@ -0,0 +1,40 @@ +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::cell::RefCell; +use std::rc::Rc; +impl Solution { + pub fn min_diff_in_bst(root: Option>>) -> i32 { + const inf: i32 = 1 << 30; + let mut ans = inf; + let mut pre = -inf; + + fn dfs(node: Option>>, ans: &mut i32, pre: &mut i32) { + if let Some(n) = node { + let n = n.borrow(); + dfs(n.left.clone(), ans, pre); + *ans = (*ans).min(n.val - *pre); + *pre = n.val; + dfs(n.right.clone(), ans, pre); + } + } + + dfs(root, &mut ans, &mut pre); + ans + } +} diff --git a/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.ts b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.ts new file mode 100644 index 0000000000000..9568814eb42f1 --- /dev/null +++ b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/Solution.ts @@ -0,0 +1,28 @@ +/** + * 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 minDiffInBST(root: TreeNode | null): number { + let [ans, pre] = [Infinity, -Infinity]; + const dfs = (root: TreeNode | null) => { + if (!root) { + return; + } + dfs(root.left); + ans = Math.min(ans, root.val - pre); + pre = root.val; + dfs(root.right); + }; + dfs(root); + return ans; +}