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.
查找二叉树最大深度,采用的是递归的方式:每个结点查找左右子树长度,比较左右子树深度,保留较长深度。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
int depth=0;
if(root!=NULL)
{
int leftDepth=maxDepth(root->left);
int rightDepth=maxDepth(root->right);
if(leftDepth>=rightDepth)
depth=leftDepth+1;
else
depth=rightDepth+1;
}
return depth;
}
};