Height of a binary tree

前端 未结 4 1925
庸人自扰
庸人自扰 2021-01-30 10:59

Consider the following code:

public int heightOfBinaryTree(Node node)
{
    if (node == null)
    {
        return 0;
    }
    else
    {
        return 1 +
            


        
4条回答
  •  囚心锁ツ
    2021-01-30 11:33

    The logic behind that code is:

    since a node will have two children, the height of the Tree will be maximum of the heights of tree whose roots are the left child and right child, and of course +1 for the walk to the children.

    As you can see, the description above is recursive and so is the code.

    BFS should also do, but it would be an overkill as both implementation and space/time complexity.

    There is a say, recursive functions though hard to understand, but are very elegant to implement.

提交回复
热议问题