首页 > 编程语言 > 详细

【算法 笔记1】查找二叉树实现

时间:2020-05-21 01:02:31      阅读:56      评论:0      收藏:0      [点我收藏+]
function Node(data,left,right){
    this.data = data
    this.left = left
    this.right = right
}
function BST(){
    this.root = null
}
BST.prototype.insert = function(data){
    var node = new Node(data,null,null)
    if(!this.root) {
        this.root = node
    }else {
        var current = this.root,parent = null
        while(true) {
            parent = current
            if(data < current.data) {
                current = current.left
                if(!current) {
                    return parent.left = node
                }
            }else {
                current = current.right
                if(!current) {
                    return parent.right = node
                } 
            }
        }
    }
}
BST.prototype.inOrder = function(node){
    if(node) {
        this.inOrder(node.left)
        console.log(node.data)
        this.inOrder(node.right)
    }
}
BST.prototype.preOrder = function(node){
    if(node) {
        console.log(node.data)
        this.inOrder(node.left)
        this.inOrder(node.right)
    }
}
BST.prototype.postOrder = function(node){
    if(node) {
        this.inOrder(node.left)
        this.inOrder(node.right)
        console.log(node.data)
    }
}
BST.prototype.getMin = function(){
    var current = this.root
    while(current.left){
        current = current.left
    }
    return current.data
}
BST.prototype.getMax = function(){
    var current = this.root
    while(current.right){
        current = current.right
    }
    return current.data
}
BST.prototype.find = function(data){
    var current = this.root
    while(current){
        if(current.data === data){
            return current
        }
        if(current.data > data) {
            current = current.left
        }
        if(current.data < data) {
            current = current.right
        }
    }
    return null
}
var Bst = new BST()

Bst.insert(1)
Bst.insert(2)
Bst.insert(4)
Bst.insert(1)
console.log(Bst.find(4))
console.log(Bst.getMax())
console.log(Bst.getMin())

【算法 笔记1】查找二叉树实现

原文:https://www.cnblogs.com/seny-33/p/12927284.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!