LeetCode104-Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

问题比较直接,用DFS搜索就行。如果只有一个根节点,那么就是0。如果是一个两层的完全二叉树,那么就是1,如果根只有一个孩子那也是1。。。然后依次类推即可,直到到了叶子节点。

C语言代码:

int maxDepth(struct TreeNode* root) {

    if( root==NULL )
    {
       return 0;
    }
    int left= maxDepth(root->left);
    int right =maxDepth(root->right);
    int res= left>right?left+1:right+1;
    return res;
}

 

posted on 2015-11-09 15:19  露台上对望  阅读(122)  评论(0编辑  收藏  举报

导航