给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
返回它的最大深度 3 。
思路:递归,分别求左右两颗子树的最大深度,一直求到把所有的叶子节点遍历完为止
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
static const auto init = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL)
return 0;
int value = 1;
int maxLeftValue = 1;
int maxRightValue = 1;
TreeNode* rootNode = root;
if (rootNode->left != NULL || rootNode->right != NULL)
value++;
// 先遍历左子树
if (rootNode->left != NULL)
{
maxLeftValue = maxLeftValue + this->maxDepth(rootNode->left);
}
// 再遍历右子树
if (rootNode->right != NULL)
{
maxRightValue = maxRightValue + this->maxDepth(rootNode->right);
}
value = maxLeftValue > maxRightValue ? maxLeftValue : maxRightValue;
return value;
}
};