欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

关于js二叉树查询遍历插入翻转的代码

程序员文章站 2022-04-06 11:22:06
...
这篇文章主要介绍了关于js二叉树查询遍历插入翻转的代码,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
function BST(){
        this.root = null
        this.insert = insert
        this.find = find
        this.mirror = mirror;
        
    }
    function Node(data,left,right){
        this.data = data
        this.left = left
        this.right = right
        this.show = show
    }
    function show() {
       return this.data;
    }
    function mirror(root){
        if(root == null){
            return
        }
        if(root.left == null && root.right == null){
            return
        }
        let temp = root.left;
        root.left = root.right;
        root.right = temp;
        mirror(root.left)
        mirror(root.right)
    }
    function insert(data){
        var n = new Node(data,null,null)
        if(this.root == null){
            this.root = n
        }else{
            var current = this.root
            while(true){
                if(data < current.data){
                    if(current.left == null){
                        current.left = n
                        break
                    }
                    current = current.left
                }else{
                    if(current.right == null){
                        current.right = n
                        break
                    }
                    current = current.right
                }
            }
        }
    }
    function find(data){
        var current = this.root
        while(true){
            if(data == current.data){
                return current
            }
            current = data < current.data ? current.left : current.right
            if(current == null){
                return null
            }
        }
    }
    function inorder(node){
        if(!(node == null)){
            inorder(node.left)
            console.log(node.show())
            inorder(node.right)
        }
    }
    var nums = new BST()
    nums.insert(23)
    nums.insert(22)
    nums.insert(16)
    nums.insert(5)
    nums.insert(3)
    nums.insert(99)
    nums.insert(22)
    inorder(nums.root)  
    mirror(nums.root)
    console.log(nums.root)

很简单的 看就完了。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

关于js的模板方法模式的讲解

如何通过Vue.js使用Font Awesome实现小图标

关于js数组filter的用法

以上就是关于js二叉树查询遍历插入翻转的代码的详细内容,更多请关注其它相关文章!