Binary Tree Height

后端 未结 8 2082
迷失自我
迷失自我 2020-12-29 12:34

I need a general formula to calculate the minimum height of the binary tree and the maximum height of the binary tree. (not the binary search tree)

8条回答
  •  旧巷少年郎
    2020-12-29 13:37

    If a root can have any number of leaves up to 2 (0,1,2) then:

    • The max height is n-1. This is the case when your tree has only one leaf. No node has more than one branch.
    • The min height is [log2(n)] where [x] is the integer part of x.

    In order to obtain a minimal height every root must have as many branches as possible. In this case you'll notice that for n=1, height=0 ; for n=2 to n=3, height=1; for n=4 to n=7, height=2 ; for n=8 to n=15, height=3 etc.

    You can thus notice that, for every n, there exists a p such that:

    2^p <= n < 2^(p+1) and p=height, so height = [log2(n)]

提交回复
热议问题