目录
题目描述:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
C++
/**
* 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 root == NULL ? 0:max(maxDepth(root->left), maxDepth(root->right)) + 1; // 每进入一次加1
}
};
下面的代码容易理解点:
执行用时:4 ms, 在所有 C++ 提交中击败了93.53%的用户
内存消耗:18.4 MB, 在所有 C++ 提交中击败了69.35%的用户
/**
* 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;
return max(1 + maxDepth(root->left), 1 + maxDepth(root->right)); // 加一,即加上当前节点深度,然后再看左右节点深度。
}
};
python
执行用时:20 ms, 在所有 Python 提交中击败了94.52%的用户
内存消耗:15.9 MB, 在所有 Python 提交中击败了16.57%的用户
通过测试用例:39 / 39
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None: return 0
return max(1+self.maxDepth(root.left), 1+self.maxDepth(root.right))