二叉查找树的实现(中序、前序、后序遍历的实现)

二叉树和二叉查找树的区别:

二叉树:每个节点的子节点不允许超过两个。 

二叉查找树:每个节点的子节点不允许超过两个,同时相对较小的值保存在左节点中, 较大的值保存在右节点中。

关于中序、前序、后序遍历的理解:

  以从整体角度到分支的角度进行考虑,假设一个小的二叉查找树有三个节点,父节点、左子节点、右子节点,中序遍历是左子节点、父节点、右子节点;前序是父节点、左子节点、右子节点;后序是左子节点、右子节点、父节点。

    function Node(data, left, right) {
        this.data = data;
        this.left = left;
        this.right = right;
        this.show = show;
    }
    function show() {
        return this.data;
    }
    function BST() {
        this.root = null;
        this.insert = insert;
    }
    function insert(data) {
        var n = new Node(data, null, null);
        if (this.root == null) {
            this.root = n;
        } else {
            var current = this.root;
            var parent;
            while (true) {
                parent = current;
                if (data < current.data) {
                    current = current.left;
                    if (current == null) {
                        parent.left = n;
                        break;
                    }
                } else {
                    current = current.right;
                    if (current == null) {
                        parent.right = n;
                        break;
                    }
                }
            }
        }
    }
    function inOrder(node) {
        if (node != null) {
            inOrder(node.left);
            document.write(node.show() + " ");
            inOrder(node.right);
        }
    }
    var nums = new BST();
    nums.insert(23);
    nums.insert(45);
    nums.insert(16);
    nums.insert(37);
    nums.insert(3);
    nums.insert(99);
    nums.insert(22);
    document.write("Inorder traversal: " + "<br />");
    inOrder(nums.root);
    document.write("<br />");

    function preOrder(node) {
        if (node != null) {
            document.write(node.show() + " ");
            preOrder(node.left);
            preOrder(node.right);
        }
    }
    document.write("Preorder traversal: " + "<br />");
    preOrder(nums.root);
    document.write("<br />");

    function postOrder(node) {
        if (node != null) {
            postOrder(node.left);
            postOrder(node.right);
            document.write(node.show() + " ");
        }
    }
    document.write("Postorder traversal: " + "<br />");
    postOrder(nums.root);
    /*上述程序运行结果为:
    Inorder traversal: 
    3 16 22 23 37 45 99 
    Preorder traversal: 
    23 16 3 22 45 37 99 
    Postorder traversal: 
    3 22 16 37 99 45 23 */
原文地址:https://www.cnblogs.com/feile/p/5391492.html