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.
题解:典型的回溯问题,就是不断选择向左向右去查找。
/**
* 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 count=1;
if(root==NULL)return 0;
else if (root->left==NULL&&root->right!=NULL){
count=1+maxDepth(root->right);
}
else if(root->left!=NULL&&root->right==NULL){
count=1+maxDepth(root->left);
}
else if (root->left==NULL&&root->right==NULL){
return count;
}
else if(root->left!=NULL&&root->right!=NULL){
int a=maxDepth(root->left);
int b=maxDepth(root->right);
if(a>=b){count=1+a;}
else{
count=1+b;
}
}
return count;
}
};