How to calculate the depth of a binary search tree

前端 未结 10 1811
说谎
说谎 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:30

    This solution is even more simpler.

    public int getHeight(Node root)
    {
        if(root!=null)
            return 1+ Math.max(getHeight(root.leftchild),getHeight(root.rightchild));
        else
            return 0;
    }
    
    0 讨论(0)
  • 2020-12-05 15:30
    public int numberOfNodes()
    {
       // This node.
       int result = 1;
    
       // Plus all the nodes from the left node.
       Node left = getLeft();
       if (left != null)
           result += left.numberOfNodes();
    
       // Plus all the nodes from the right node.
       Node right = getRight();
       if (right != null)
           result += right.numberOfNodes();
    
       return result;
    }
    
    0 讨论(0)
  • 2020-12-05 15:34
    int maxDepth(Node node) {
        if (node == null) {
            return (-1); // an empty tree  has height −1
        } else {
            // compute the depth of each subtree
            int leftDepth = maxDepth(node.left);
            int rightDepth = maxDepth(node.right);
            // use the larger one
            if (leftDepth > rightDepth )
                return (leftDepth + 1);
            else
                return (rightDepth + 1);
        }
    }
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-05 15:34
    public class Node {
       private Node left; 
       private Node right;
       public int size() { return 1+ (left==null?0:left.size())+ (right==null?0:right.size());}
    }
    
    0 讨论(0)
  • 2020-12-05 15:35
    private static int getNumberOfNodes(Node node) {
        if (node == null) {
            return 0;
        }
    
        return 1 + getNumberOfNodes(node.left) + getNumberOfNodes(node.right);
    }
    
    0 讨论(0)
提交回复
热议问题