慕粉3555700
2020-02-07 12:53
<!DOCTYPE html>
<html>
<head>
<title>binaryTree</title>
</head>
<body>
<script type="text/javascript">
function BinaryTree(){
var Node = function(key){
this.key = key;
this.left = null;
this.right = null;
};
var root = null;
this.insert = function(key){
var newNode = new Node(key);
if(root == null){
root = newNode;
}else{
insertNode(root,newNode);
}
};
var insertNode = function(node,newNode){
if(newNode.key < node.key){
if(node.left == null){
node.left = newNode.key;
}else{
insertNode(node.left,newNode);
}
}else{
if(node.right == null){
node.right = newNode.key;
}else{
insertNode(node.right,newNode);
}
}
};
}
var nodes = [8,3,10,1,6,14,4,7,13];
var binaryTree = new BinaryTree();
nodes.forEach(function(key){
binaryTree.insert(key);
});
</script>
</body>
</html>
第一 判断是否等于null 用=== 不是 ==
第二node.left = newNode.key;不对 是node.left = newNode;
同理right也是
Javascript实现二叉树算法
46934 学习 · 97 问题
相似问题