Depth of a binary tree:
Depth of a binary tree is the maximum length of all paths. Nodes from the root to a leaf form a path.
A binary Tree with depth 4 |
Solution: Depth of a binary tree is the length of the longest
path.
If a binary tree has only one node, its depth is 1. If
the root node of a binary tree has only a left sub-tree, its depth is the depth
of the left sub-tree plus 1(root node). Similarly, its depth is the depth of
the right sub-tree plus 1(root node) if the root node has only a right sub-tree.
What if the root node has both left sub-tree and right sub-tree? It is the
greater/max value of the depth of the left and right sub-trees plus 1(root node).
For example, the root node of the binary tree in the
above figure has both left and right sub-trees. The depth of the left sub-tree
rooted at node 2 is 3, and the depth of the right sub-tree rooted at node 3 is
2, so the depth of the whole binary tree is 4; 1 plus the greater value of 3
and 2.
It is easy to implement this solution
recursively, with little modification on the post-order traversal
algorithm, as shown below:
algorithm, as shown below:
int TreeDepth(Binarytree Node* pRoot)
{
int nLeft, nRight;
if(root == NULL)
return 0;
nLeft
= TreeDepth(pRoot->pLeft);
nRight
= TreeDepth(pRoot->pRight);
return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1);
}