How to calculate the depth of a binary search tree

前端 未结 10 1858
说谎
说谎 2020-12-05 15:11

I would like to calculate the summation of the depths of each node of a Binary Search Tree.

The individual depths of the elements are not already stored.

10条回答
  •  情深已故
    2020-12-05 15:34

    public int countNodes(Node root)
    {  
       // Setup
       // assign to temps to avoid double call accessors. 
       Node left = root.getLeft();
       Node right = root.getRight();
       int count = 1; // count THIS node.
    
       // count subtrees
       if (left != null) count += countNodes(left);
       if (right != null) count += countNodes(right);
    
       return count;
    }
    

提交回复
热议问题