跳到主要内容

104 二叉树的最大深度

https://leetcode.cn/leetbook/read/top-interview-questions-easy/xnd69e/

https://leetcode.cn/problems/maximum-depth-of-binary-tree/description/

cost: 1m42s

/**
* 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 maxDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int n1 = this->maxDepth(root->left);
int n2 = this->maxDepth(root->right);
return n1 > n2 ? n1 + 1 : n2 + 1;
}
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)