How to calculate the depth of a binary search tree

2019-01-14 13:10发布

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条回答
不美不萌又怎样
2楼-- · 2019-01-14 13:22
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;
}
查看更多
神经病院院长
3楼-- · 2019-01-14 13:32
int depth(treenode *p)
{
   if(p==NULL)return(0);
   if(p->left){h1=depth(p->left);}
   if(p=>right){h2=depth(p->right);}
   return(max(h1,h2)+1);
}
查看更多
The star\"
4楼-- · 2019-01-14 13:36

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;
}
查看更多
Summer. ? 凉城
5楼-- · 2019-01-14 13:36
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;
}
查看更多
登录 后发表回答