数据结构133-二叉树插入操作代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>封装二叉搜索树</title>
</head>
<body>
    <script>
        function BinarySearchTree(){
            function Node(key){
                this.key=null
                this.left=null
                this.right-null
            }
            this.root=null

            BinarySearchTree.prototype.insert=function(key){
                var newNode=new Node(key)
                //判断节点是否有值
                if(this.root==null){
                    this.root=newNode
                }else{
                    this.insertNode(this.root,newNode)
                }
            }
            BinarySearchTree.prototype.insertNode=function(node,newNode){
                if(newNode.key<node.key){
                    if(node.left==null){
                        node.left=newNode
                    }else{
                        this.insertNode(node.left,newNode)
                    }
                }else{
                    if(node.right==null){
                        node.right=newNode
                    }else{
                        this.insertNode(node.right,newNode)
                    }
                }
            }

        }
    </script>
</body>
</html>

posted @ 2022-12-18 10:12  前端导师歌谣  阅读(21)  评论(0)    收藏  举报