js实现创建二叉树+中序遍历

二叉树概念

1.除了最下面一层,每个节点都是父节点,每个节点都有且最多有两个子节点;

2.除了嘴上面一层,每个节点是子节点,每个节点都会有一个父节点;

3.最上面一层的节点为根节点;

图例说明:

中序遍历概念

先打印左子树(左子节点),接着打印父节点,最后打印右子树(右子节点)

图例说明:

最后贴代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script>
        //创建二叉树
        function Node(data,left,right){
            this.data = data;
            this.left = left;
            this.right = right;
        }
        Node.prototype.show = function(){
            return this.data;
        }
        function BST(){
            this.root = null;
        }
        BST.prototype.insert = function(data){
            var node = new Node(data,null,null);
            if(this.root == null){
                this.root = node;
            }else{
                var current = this.root;
                var parent;
                while(true){
                    parent = current;
                    if(data < current.data){
                        current = current.left;
                        if(current == null){
                            parent.left = node;
                            break;
                        }
                    }else{
                        current = current.right;
                        if(current == null){
                            parent.right = node;
                            break;
                        }
                    }
                }
            }
        }
        //二叉树中序遍历
        BST.prototype.inOrder = function(node){
            if(node){
                this.inOrder(node.left);
                console.log(node.show() + " ");
                this.inOrder(node.right);
            }
        }
        //测试数据
        var bst  = new BST();
        var nums = [10,3,18,2,4,13,21,9,8,9];
        for(var i = 0;i < nums.length;i ++){
            bst.insert(nums[i]);
        }
        bst.inOrder(bst.root);
    </script>
</body>
</html>

 

转载于:https://www.cnblogs.com/xiaohualu/p/10308504.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值