首页 > web前端 > js教程 > 正文

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

不言
发布: 2018-07-14 17:27:28
原创
1825 人浏览过

这篇文章主要介绍了关于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二叉树查询遍历插入翻转的代码的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!