97 Maximum depth of a binary tree

Original title URL: http://www.lintcode.com/zh-cn/problem/maximum-depth-of-binary-tree/#

Given a binary tree, find its maximum depth.

The depth of a binary tree is the distance from the root node to the farthest leaf node.

Sample

Given a binary tree as follows:

  1
 / \ 
2   3
   / \
  4   5

The maximum depth of this binary tree is 3.

Label 
 
Ideas: If you have done a balanced binary tree before, this problem is very easy... recursion, the code should not be difficult to understand.
 
AC code:
/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: The root of binary tree.
     * @return: An integer
     */
    int maxDepth(TreeNode * root) {
        // write your code here
         if (root==NULL)
     {
         return 0;
     }
     int leftDepth=maxDepth(root->left);
     int rightDepth=maxDepth(root->right);
     return max(leftDepth,rightDepth)+1;
    }
};

 

 
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324590064&siteId=291194637