mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-25 15:06:30 +08:00
fix dart code for binary_search_tree (#711)
This commit is contained in:
parent
95bc0ffdb2
commit
233e842d63
1 changed files with 9 additions and 19 deletions
|
@ -12,9 +12,9 @@ class BinarySearchTree {
|
||||||
late TreeNode? _root;
|
late TreeNode? _root;
|
||||||
|
|
||||||
/* 构造方法 */
|
/* 构造方法 */
|
||||||
BinarySearchTree(List<int> nums) {
|
BinarySearchTree() {
|
||||||
nums.sort(); // 排序数组
|
// 初始化空树
|
||||||
_root = buildTree(nums, 0, nums.length - 1); // 构建二叉搜索树
|
_root = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 获取二叉树的根节点 */
|
/* 获取二叉树的根节点 */
|
||||||
|
@ -22,19 +22,6 @@ class BinarySearchTree {
|
||||||
return _root;
|
return _root;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 构建二叉上搜索树 */
|
|
||||||
TreeNode? buildTree(List<int> nums, int i, int j) {
|
|
||||||
if (i > j) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
// 将数组中间节点作为根节点
|
|
||||||
int mid = (i + j) ~/ 2;
|
|
||||||
TreeNode? root = TreeNode(nums[mid]);
|
|
||||||
root.left = buildTree(nums, i, mid - 1);
|
|
||||||
root.right = buildTree(nums, mid + 1, j);
|
|
||||||
return root;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* 查找节点 */
|
/* 查找节点 */
|
||||||
TreeNode? search(int num) {
|
TreeNode? search(int num) {
|
||||||
TreeNode? cur = _root;
|
TreeNode? cur = _root;
|
||||||
|
@ -87,7 +74,6 @@ class BinarySearchTree {
|
||||||
void remove(int num) {
|
void remove(int num) {
|
||||||
// 若树为空,直接提前返回
|
// 若树为空,直接提前返回
|
||||||
if (_root == null) return;
|
if (_root == null) return;
|
||||||
|
|
||||||
TreeNode? cur = _root;
|
TreeNode? cur = _root;
|
||||||
TreeNode? pre = null;
|
TreeNode? pre = null;
|
||||||
// 循环查找,越过叶节点后跳出
|
// 循环查找,越过叶节点后跳出
|
||||||
|
@ -136,8 +122,12 @@ class BinarySearchTree {
|
||||||
/* Driver Code */
|
/* Driver Code */
|
||||||
void main() {
|
void main() {
|
||||||
/* 初始化二叉搜索树 */
|
/* 初始化二叉搜索树 */
|
||||||
List<int> nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
|
BinarySearchTree bst = BinarySearchTree();
|
||||||
BinarySearchTree bst = BinarySearchTree(nums);
|
// 请注意,不同的插入顺序会生成不同的二叉树,该序列可以生成一个完美二叉树
|
||||||
|
List<int> nums = [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15];
|
||||||
|
for (int num in nums) {
|
||||||
|
bst.insert(num);
|
||||||
|
}
|
||||||
print("\n初始化的二叉树为\n");
|
print("\n初始化的二叉树为\n");
|
||||||
printTree(bst.getRoot());
|
printTree(bst.getRoot());
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue