最近自己犯了一個愚蠢至極的錯誤,被問到如何計算一顆平衡二叉樹的高度,居然一時沒想起來,其實答案相當(dāng)簡單,用句老師們經(jīng)常愛講的話就是,這是道送分題啊,結(jié)果自己居然沒把握住...(真恨不得弄死自己)
言歸正傳,如果知道一棵平衡樹的元素數(shù)目m,則二叉樹的高度為log2m,由此可寫出代碼
public class BinaryTreeNode<T> {
public T element;
public BinaryTreeNode<T> left, right;
public BinaryTreeNode(T element) {
this.element = element;
this.left = null;
this.right = null;
}
public int numChildren() {
int childrenCount = 0;
if (left != null) {
childrenCount = 1 + left.numChildren();
}
if (right != null) {
childrenCount = childrenCount + 1 + right.numChildren();
}
return childrenCount;
}
public int getHeight(int nodesNum) {
return (int)(Math.log(nodesNum) / Math.log(2));
}
}