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.
分析
题意是:给定一颗二叉树,求出它的最大深度
对树的问题,递归总是一种思路。对于这个求二叉树深度的问题,我们可以归结出这样一种思路,从根节点开始 求出它的左子树深度leftDepth和右子树深度rightDepth,求出leftDepth和rightDepth的最大值,那么再加一就是根 点的最大深度;递归的执行下去,结束条件就是当节点是叶子节点是,返回深度1。
Code
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode *root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if( !root )
return 0;
int leftDepth = 0, rightDepth = 0;
if( root->left )
leftDepth = maxDepth(root->left);
if( root->right )
rightDepth = maxDepth(root->right);
return 1 + std::max(leftDepth, rightDepth);
}
};