题目如下:
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.
递归地求maximum depth.
/**
* Definition for binary tree
* 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;
TreeNode* left_node = root->left;
TreeNode* right_node = root->right;
int left_dep = maxDepth(left_node);
int right_dep = maxDepth(right_node);
return 1 + ((left_dep > right_dep) ? left_dep:right_dep); //注意三目运算符优先级比加号低,所以要用括号括起来。
}
};
类似的题目是 (111) Minimum Depth of Binary Tree, 在这里