返回
用Java、C++和Rust解决LeetCode 669:修剪二叉搜索树
后端
2023-11-01 07:27:23
序言
LeetCode 669是一道考察二叉搜索树操作的算法题。任务是给定一个二叉搜索树和两个整数low
和high
,修剪该树,使得修剪后的树满足所有节点的值均在区间[low
, high
]内。
本博客将分别用Java、C++和Rust三种语言对该题进行详细讲解和代码实现。同时,我们还将深入探究这些语言中与二叉搜索树相关的类和方法。
Java 题解
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
if (root == null) {
return null;
}
if (root.val < low) {
return trimBST(root.right, low, high);
} else if (root.val > high) {
return trimBST(root.left, low, high);
} else {
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
return root;
}
}
}
类和方法:
TreeNode
:Java中的二叉树节点类val
:节点的值left
:左子树right
:右子树
时间复杂度: O(N),其中N是树中的节点数。
C++ 题解
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if (!root) {
return nullptr;
}
if (root->val < low) {
return trimBST(root->right, low, high);
} else if (root->val > high) {
return trimBST(root->left, low, high);
} else {
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
return root;
}
}
};
类和方法:
TreeNode
:C++中的二叉树节点结构体val
:节点的值left
:左子树right
:右子树
时间复杂度: O(N),其中N是树中的节点数。
Rust 题解
// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
val: i32,
left: Option<Rc<RefCell<TreeNode鞭>,
right: Option<Rc<RefCell<TreeNode>,
}
impl TreeNode {
#[inline]
fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}
use std::cell::Rc;
use std::rc::RefCell;
impl Solution {
pub fn trim_bst(root: Option<Rc<RefCell<TreeNode>,>, low: i32, high: i32) -> Option<Rc<RefCell<TreeNode>,> {
if root.is_none() {
return None;
}
let mut root = root.unwrap();
if root.borrow().val < low {
return Self::trim_bst(root.borrow_mut().right.take(), low, high);
} else if root.borrow().val > high {
return Self::trim_bst(root.borrow_mut().left.take(), low, high);
} else {
root.borrow_mut().left = Self::trim_bst(root.borrow_mut().left.take(), low, high);
root.borrow_mut().right = Self::trim_bst(root.borrow_mut().right.take(), low, high);
Some(root)
}
}
}
类和方法:
TreeNode
:Rust中的二叉树节点结构体val
:节点的值left
:左子树right
:右子树Option<Rc<RefCell<TreeNode>,>
:表示二叉树节点的可选引用(Rust特有的所有权机制)
时间复杂度: O(N),其中N是树中的节点数。