树的最大深度问题
树的最大深度求解方法利用的遍历递归的同时给深度加一,这里的遍历只是遍历到叶子节点的位置。
/**
* 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) {
if(!root) return 0;
int nleft=maxDepth(root->left);
int nright=maxDepth(root->right);
return max(nleft,nright)+1;
}
};