原题链接:104. 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.
题意:就是给你一颗树,要你得出这颗树最深有多少个节点
思路:用分治的思想,从最下层的节点开始,递归得出每个节点下的最深深度,再求这个节点上一个节点最深的深度,直到最上层根节点,便可以得出这棵树的最深深度了
ac代码:
/**
* 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 == NULL) return 0;
if(root->left==NULL&&root->right==NULL) return 1;
int maxleft=maxDepth(root->left);
int maxright=maxDepth(root->right);
return maxleft>maxright?maxleft+1:maxright+1;
}
};