问题描述
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的距离。
样例
给出一棵如下的二叉树:
这个二叉树的最大深度为3.
求解
注意题目中“深度”的定义与标准定义不同,标准定义中“深度”指根结到某结点路径的长度,样例中最大深度应为2.
以下是按题目要求给出的代码:
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int maxDepth(TreeNode *root) {
// write your code here
if(root == nullptr) return 0;
int leftDepth = maxDepth(root -> left) + 1;
int rightDepth = maxDepth(root -> right) + 1;
return std::max(leftDepth, rightDepth);
}
};