[LeetCode] 104. 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) {
return findDepth(root, 0);
}
private:
int findDepth(TreeNode* node, int dis) {
if (node != NULL) {
return max(findDepth(node->left, dis + 1), findDepth(node->right, dis + 1));
} else {
return dis;
}
}
};