二叉排序树
(1) 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值(查找最小值就是查找最左的节点) (2) 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值(查找最大值就是查找最右节点了) (3) 它的左、右子树也分别为二叉查找树
function BinarySearchTree(keys){
let Node = function (key){
this.key = key
this.left = null
this.right = null
}
let root = null
let insertNode = (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 = (key)=>{
let newNode = new Node(key)
if (root === null) {
root = newNode
}else {
insertNode(root,newNode)
}
}
keys.forEach((key)=>{
this.insert(key)
})
return root
}
const keys = [8,3,10,1,6,14,4,7,13]
BinarySearchTree(keys)
中序遍历 左根右按顺序遍历
function BinaryTree(){
var inOrderTraverseNode = function(node,callback){
if(node !== null){
inOrderTraverseNode(node.left,callback);
callback(node.key);
inOrderTraverseNode(node.right,callback);
}
}
this.inOrderTraverse = function(oRoot,callback){
inOrderTraverseNode(oRoot,callback);
}
};
var callback = function(key){
console.log(key);
};
binaryTree.inOrderTraverse(oRoot,callback);
前序遍历 根左右按顺序遍历
后序遍历 左右根按顺序遍历
|