zoukankan      html  css  js  c++  java
  • 二叉搜索树

    class BinarySearchTree:
        def __init__(self, value):
            self.value = value
            self.left_child = None
            self.right_child = None
        
        def insert_node(self, value):
            if value <= self.value and self.left_child:
                self.left_child.insert_node(value)
            elif value <= self.value:
                self.left_child = BinarySearchTree(value)
            elif value > self.value and self.right_child:
                self.right_child.insert_node(value)
            else:
                self.right_child = BinarySearchTree(value)
    
        def in_order(self):
            if self.left_child:
                self.left_child.in_order()
            print(self.value)
            if self.right_child:
                self.right_child.in_order()
    
        def find_node(self, value):
            if value < self.value and self.left_child:
                return self.left_child.find_node(value)
            
            if value > self.value and self.right_child:
                return self.right_child.find_node(value)
            
            return value == self.value
    
        def find_min_value(self):
            if self.left_child:
                return self.left_child.find_min_value()
            else:
                return self.value
     
    
    a_node = BinarySearchTree(5)
    a_node.insert_node(4)
    a_node.insert_node(6)
    a_node.insert_node(1)
    a_node.insert_node(7)
    a_node.insert_node(3)
    a_node.insert_node(2)
    a_node.in_order()
    print(a_node.find_node(14))
    print(a_node.find_min_value())
    
  • 相关阅读:
    Leetcode424. 替换后的最长重复字符
    Leetcode82. 删除排序链表中的重复元素 II
    python 无序模块,hashlib模块
    python 内置方法
    python 面向对象的三大特性
    python 面向对象
    python 递归函数和二分查找
    python 装饰器
    python 函数名,闭包
    python 函数进阶
  • 原文地址:https://www.cnblogs.com/KbMan/p/14345120.html
Copyright © 2011-2022 走看看