Problem:
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.
题意是求二叉树的最大深度。有两种方法,第一种是先求左树最大深度,然后求右树的最大深度,然后取两者较大值加一。
Code:(LeetCode运行6ms)
/**
* 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;
}
int max_left = maxDepth(root -> left);
int max_right = maxDepth(root -> right);
return max(max_left, max_right) + 1;
}
};