• 当前标签:二叉树

程序开发 二叉排序树

二叉排序树或者是一棵空树,或者是具有下列性质的二叉树: (1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值; (2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值; (3)左、右子树也分别为二叉排序树; (4)没有键值相等的节点。 function BinaryTree() { const Node = function (key) { this.key = key; this.left = null; this.right = null; }; let root = null; const insertNode = function (node, newNode) { if (newNode.key < node.key) { if (node.left === null) { node.left = newNode; } else { insertNode(node.left, newNode); } } else { if (node.right === null) { node.right = newNode; } else { insertNode(node.right, newNode); } } } this.insert = function (key) { let newNode = new Node(key); if (root === null) { root = newNode; } else { insertNode(root, newNode) } }; const inOrderTraverseNode = function (node, callback) { if (node !== null) { inOrderTraverseNode(node.left, callback); callback(node.key); inOrderTraverseNode(node.right, callback); } } // 中序遍历 this.inOrderTraverse = function (callback) { inOrderTraverseNode(root, callback); } const preOrderTraverseNode = function (node, callback) { if (node !== null) { callback(node.key); preOrderTraverseNode(node.left, callback); preOrderTraverseNode(node.right, callback); } } // 前序遍历 this.preOrderTraverse = function (callback) { preOrderTraverseNode(root, callback); } const postOrderTraverseNode = function

2019-03-08 14:50:41 56 0 0
阅读详情
  • 1
前往