一、题目:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
二、解题思路:
递归深度遍历二叉树,先左子树再右子树,最后返回左右子树深度的最大值+1(根节点)。
三、代码和结果:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };*/
class Solution {
public:
int getDepth(TreeNode* node) {
if (node == NULL) return 0;
int leftDepth = getDepth(node->left); // 左
int rightDepth = getDepth(node->right); // 右
int depth = max(leftDepth, rightDepth); // 中
return depth+1;
}
int maxDepth(TreeNode* root) {
return getDepth(root);
}
};
/*
这个是精简版,核心思想是一样的:
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==0)return 0;
return 1+max(maxDepth(root->left),maxDepth(root->right));
}
};
*/
结果:
做完这道题可以继续做,多叉树的最大深度,博文:多叉树的最大深度
参考文章:二叉树的最大深度(详解)