Counting nodes in a tree in Java

前端 未结 15 1622
我寻月下人不归
我寻月下人不归 2020-12-03 00:03

First of all, I swear this is not homework, it\'s a question I was asked in an interview. I think I made a mess of it (though I did realise the solution requires recursion).

相关标签:
15条回答
  • 2020-12-03 00:29

    Questions related to binary tree should be expected in an interview. I would say to take time before any next interview and go through this link. There are about 14 problems solved .You can have a look and how the solution is done. This would give you an idea of how to tackle a problem with binary tree in future.

    I know your question is specific to the count method .That is also implemented in the link that i provided

    0 讨论(0)
  • 2020-12-03 00:32
    return (getRightChild() == null ? 0 : getRightChild.count()) + (getLeftChild() == null ? 0 : getLeftChild.count()) + 1;
    

    Or something like that.

    0 讨论(0)
  • 2020-12-03 00:38
    class Tree {
    
      Tree getRightChild() {
        // Assume this is already implemented
      }
    
      Tree getLeftChild() {
        // Assume this is already implemented
      }
    
      int count() {
       return 1 
          + getRightChild() == null? 0 : getRightChild().count()
          + getLeftChild() == null? 0 : getLeftChild().count();
      }
    }
    
    0 讨论(0)
提交回复
热议问题