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.
解题方法:
递归算法:若root为空,则返回0。否则返回其左子树maximum depth +1 和 右子树maximum depth + 1的较大者。
代码详情:
/**
* 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;
} else {
int num1 = maxDepth(root->left);
int num2 = maxDepth(root->right);
return num1>=num2 ? num1+1:num2+1;
}
}
};