Skip to content

feat: update solutions to lc problem: No.0537 #3318

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 2 commits into from
Jul 24, 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
187 changes: 102 additions & 85 deletions solution/0500-0599/0530.Minimum Absolute Difference in BST/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,11 @@ tags:

### 方法一:中序遍历

中序遍历二叉搜索树,获取当前节点与上个节点差值的最小值即可。
题目需要我们求任意两个节点值之间的最小差值,而二叉搜索树的中序遍历是一个递增序列,因此我们只需要求中序遍历中相邻两个节点值之间的最小差值即可。

我们可以使用递归的方法来实现中序遍历,过程中用一个变量 $\textit{pre}$ 来保存前一个节点的值,这样我们就可以在遍历的过程中求出相邻两个节点值之间的最小差值。

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

<!-- tabs:start -->

Expand All @@ -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
```
Expand All @@ -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;
}
Expand All @@ -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);
}
}
Expand All @@ -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);
}
};
```

Expand All @@ -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;
}
```

Expand All @@ -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<Rc<RefCell<TreeNode>>>) -> 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<Rc<RefCell<TreeNode>>>, 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<Rc<RefCell<TreeNode>>>, 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;
};
```

<!-- tabs:end -->
Expand Down
Loading
Loading