1.创建二叉树
function BinaryTree(data, leftChild, rightChild) {
this.data = data || null;
// 左右孩子结点
this.leftChild = leftChild || null;
this.rightChild = rightChild || null;
}
2.递归先序遍历二叉树
// 链式存储结构的递归先序遍历
BinaryTree.prototype.preOrderTraverse = function preOrderTraverse(visit) {
visit(this.data);
if (this.leftChild) preOrderTraverse.call(this.leftChild, visit);
if (this.rightChild) preOrderTraverse.call(this.rightChild, visit);
};
3.二叉树的深度
var maxDepth = function(root) {
if (root === null) { //注意等号
return 0;
} else {
var leftDepth = maxDepth(root.left),
rightDepth = maxDepth(root.right);
var childDepth = leftDepth > rightDepth ? leftDepth : rightDepth;
return childDepth + 1;//根节点不为空高度至少为1
}
};