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.
接口:
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int maxDepth(TreeNode *root) {
// write your code here
}
};
分析:
简单题目能够handle住,所以用个divide-and-conquer,返回int型。
定义结点:
struct TreeNode{
public:
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
解法:
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int maxDepth(TreeNode *root) {
// write your code here
if (root == NULL) {
return 0;
}
int left = maxDepth(root->left) + 1;
int right = maxDepth(root->right) + 1;
return max(left, right);
}
};