Are my recursion conditions right to compute binary tree height?

后端 未结 4 1739
既然无缘
既然无缘 2021-01-28 19:59

I\'m trying to know whether my code is right or wrong with your help, because sadly I can\'t run it to check.

There are no compile errors. What I\'m trying to do is to

相关标签:
4条回答
  • 2021-01-28 20:22

    Really compact version:

    public int height(RBNode t) {
        if (t == null) {
            return 0;
        }
        return Math.max(height(t.left), height(t.right)) + 1;
    }
    
    0 讨论(0)
  • 2021-01-28 20:34

    At first glance, as long as you pass in the head of the tree, it'll return the correct value. But it should have been easy to construct a test to validate this...

    0 讨论(0)
  • 2021-01-28 20:36

    Looks fine to me, although I'd personally change the last bit to:

    return Math.max(heightLeft, heightRight) + 1;
    

    I'm concerned that you can't run it at all though... why can you not write unit tests around this? I'd be nervous of any code I can't test :)

    0 讨论(0)
  • 2021-01-28 20:42

    In the code in the question, are we not getting height +1? the height is defined as 'length of the path from the root to the deepest node in the tree. A (rooted) tree with only one node (the root) has a depth of zero.'(wikipedia)

    if in question's code if give the root to a tree with just 1 node it will give height as 1, which should infact be 0..

    Please correct me if i am wrong somewhere..

    0 讨论(0)
提交回复
热议问题