首页 > 其他分享 >数据结构之树(二叉排序树)

数据结构之树(二叉排序树)

时间:2023-11-11 11:55:21浏览次数:45  
标签:val 50 二叉 之树 key print 数据结构 root 节点

特点

二叉排序树(Binary Search Tree,BST)的特点:

  1. 每个节点最多有两个子节点,分别称为左子节点和右子节点。
  2. 节点的左子树中的所有节点的值都小于该节点的值。
  3. 节点的右子树中的所有节点的值都大于该节点的值。
  4. 左子树和右子树也分别是二叉排序树。

BST的主要优点是可以实现高效的查找、插入和删除操作,时间复杂度为O(log n),其中n是树中节点的数量。这使得BST成为一种非常有用的数据结构,常被用于搜索、排序和关联数据的存储。

最佳实践

  1. 插入节点:

    • 插入节点时,首先从根节点开始,比较要插入的值和当前节点的值。
    • 如果要插入的值小于当前节点的值,就移动到左子节点;如果大于当前节点的值,就移动到右子节点。
    • 重复这个过程,直到找到一个空的位置,将新节点插入其中。
  2. 删除节点:

    • 删除节点时,首先找到要删除的节点。
    • 如果要删除的节点没有子节点,直接删除它。
    • 如果要删除的节点有一个子节点,将子节点替代被删除的节点。
    • 如果要删除的节点有两个子节点,可以选择用左子树中的最大值节点或右子树中的最小值节点来替代被删除的节点。
  3. 查找节点:

    • 查找节点时,从根节点开始,比较要查找的值和当前节点的值。
    • 如果要查找的值等于当前节点的值,就找到了目标节点。
    • 如果要查找的值小于当前节点的值,就移动到左子节点继续查找;如果大于当前节点的值,就移动到右子节点继续查找。
  4. 遍历树:

    • 中序遍历(In-order traversal)可以用来按升序顺序遍历BST的所有节点。

示例

排序树:

 

删除:20

 

删除50:

 

 

 

class TreeNode:
    def __init__(self, key):
        self.val = key
        self.left = None
        self.right = None


def insert(root, key):
    if root is None:
        return TreeNode(key)
    if key < root.val:
        root.left = insert(root.left, key)
    else:
        root.right = insert(root.right, key)
    return root


def delete(root, key):
    if root is None:
        return root
    if key < root.val:
        root.left = delete(root.left, key)
    elif key > root.val:
        root.right = delete(root.right, key)
    else:
        if root.left is None:
            return root.right
        elif root.right is None:
            return root.left
        # 因为删除的就是当前root节点,因此root节点值就变成了,其右子树最小值
        root.val = minValue(root.right)
        root.right = delete(root.right, root.val)
    return root


def minValue(node):
    current = node
    while current.left is not None:
        current = current.left
    return current.val

# 搜索
def search(root, key):
    if root is None or root.val == key:
        return root
    if root.val < key:
        return search(root.right, key)
    return search(root.left, key)

# 中序遍历
def inorder_traversal(root):
    if root:
        inorder_traversal(root.left)
        print(root.val, end=" ")
        inorder_traversal(root.right)


# 示例用法
root = None
root = insert(root, 50)
print("50 after root的值:{}", root.val)
root = insert(root, 30)
print("30 after root的值:{}", root.val)
root = insert(root, 20)
print("20 after root的值:{}", root.val)
root = insert(root, 40)
print("40 after root的值:{}", root.val)
root = insert(root, 70)
print("70 after root的值:{}", root.val)
root = insert(root, 60)
print("60 after root的值:{}", root.val)
root = insert(root, 80)
print("80 after root的值:{}", root.val)

# 中序遍历
print("Inorder遍历结果:")
inorder_traversal(root)
print("root的值:{}", root.val)

print("\n查找 40:", search(root, 40).val)

root = delete(root, 20)
print("删除 20 后的Inorder遍历结果:")
inorder_traversal(root)
print("root的值:{}", root.val)

root = delete(root, 50)
print("删除 50 后的Inorder遍历结果:")
print("root的值:{}", root.val)
inorder_traversal(root)

输出:

50 after root的值:{} 50
30 after root的值:{} 50
20 after root的值:{} 50
40 after root的值:{} 50
70 after root的值:{} 50
60 after root的值:{} 50
80 after root的值:{} 50
Inorder遍历结果:
20 30 40 50 60 70 80 root的值:{} 50

查找 40: 40
删除 20 后的Inorder遍历结果:
30 40 50 60 70 80 root的值:{} 50
删除 50 后的Inorder遍历结果:
root的值:{} 60
30 40 60 70 80 

  

 

标签:val,50,二叉,之树,key,print,数据结构,root,节点
From: https://www.cnblogs.com/allenxx/p/17825744.html

相关文章

  • python3: dlt - 数据结构2
    python3:dlt-数据结构2    一、源程序1[wit@fedoranull]$cattest.py2#!/usr/bin/envpython334567#file_name=test.py8#python_verion=3.11.1910111213#testthisscript14defmsg():15print......
  • python3: dlt - 数据结构
    python3:dlt-数据结构    一、程序:1[wit@fedoranull]$cattest.py2#!/usr/bin/envpython334567#testthisscript8defmsg():9print("\nhello,python3!\n")101112#runningmsg()13#msg()1415......
  • C++创建二叉排序树
    voidcreate(Tree&t,intval){if(t==nullptr){t=newnode;t->data=val;t->left=t->right=nullptr;}elseif(val>t->data)create(t->right,val);elseif(val<t->data)create(t->left,val);}voidinsert(Tree&......
  • 二叉树(周五实验)
    1#include<iostream>2#include<fstream>3usingnamespacestd;45typedefstructTreeNode6{7chardata;8intlevel;9TreeNode*lchid;10TreeNode*rchid;11}TreeNode;1213chararr[20][2];//存放结......
  • 什么是数据结构里的 Merkle 树
    Merkle树,也被称为"hashtree",是一种二叉树的数据结构。这种树的每个节点都是基于其子节点的一种特殊形式的hash。具体来说,叶节点的hash是由存储在那里的数据块(例如文件或文件的部分)生成的,而非叶节点的hash是由其子节点的hash生成的。如果Merkle树只有一个节点(也就是根节......
  • [左神面试指南] 二叉树[上]篇
    CDXXX用递归和非递归方式实现二叉树先序、中序和后序遍历❗publicclassCDbianli_1{publicstaticclassTreeNode{publicintval;publicTreeNodeleft;publicTreeNoderight;publicTreeNode(intnum){......
  • 数据结构之线性表
    线性表之顺序存储:1sqlist.h2#ifndef_SQLIST_H3#define_SQLIST_H45#defineMAX_SIZE66typedefstruct7{8intdata[MAX_SIZE];9intlast;10}sqlist,*sqlink;1112voidcreatList(sqlinkL);//建空表13intgetLength......
  • 面试必刷TOP101:24、二叉树的中序遍历
    题目题解深度优先搜索-递归publicclassSolution{/***代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可***@paramrootTreeNode类*@returnint整型一维数组*/publicint[]inorderTraversal(TreeNo......
  • 数据结构-队列
    一、概念1、队列的定义队列是仅限在一端进行插入,另一端进行删除的线性表。队列又被称为先进先出(FirstInFirstOut)的线性表,简称FIFO。2、队首允许进行元素删除的一端称为队首3、队尾允许进行元素插入的一端称为队尾二、接口1、可写接口(1)数据入队队列的插入操作,叫做入队。它是......
  • 数据结构入门 — 顺序表详解
    前言数据结构入门—顺序表详解关注博主,后期持续更新系列文章文章末尾有源码*****感谢观看,希望对你有所帮助*****文章目录前言一、顺序表1.顺序表是什么2.优缺点二、概念及结构1.静态顺序表2.动态顺序表三、顺序表接口实现(代码演示)1.动态存储结构2.顺序表打印3.顺序表初......