给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
3
/ \
9 20
/ \
15 7 返回它的最大深度 3
c plus
- 递归
题解class Solution {
public:
int maxDepth(TreeNode* root) {
return helper(root);
}
int helper(TreeNode *node) {
if (node == NULL) return 0;
int left = helper(node->left);
int right = helper(node->right);
return max(left, right) + 1;
}
};
Golang
func maxDepth(root *TreeNode) int {
if (root == nil){
return 0
}
ld := maxDepth(root.Left)
rd := maxDepth(root.Right)
if ld > rd {
return ld + 1
}else{
return rd + 1
}
}
%E7%BB%99%E5%AE%9A%E4%B8%80%E4%B8%AA%E4%BA%8C%E5%8F%89%E6%A0%91%EF%BC%8C%E6%89%BE%E5%87%BA%E5%85%B6%E6%9C%80%E5%A4%A7%E6%B7%B1%E5%BA%A6%E3%80%82%0A%0A%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%B7%B1%E5%BA%A6%E4%B8%BA%E6%A0%B9%E8%8A%82%E7%82%B9%E5%88%B0%E6%9C%80%E8%BF%9C%E5%8F%B6%E5%AD%90%E8%8A%82%E7%82%B9%E7%9A%84%E6%9C%80%E9%95%BF%E8%B7%AF%E5%BE%84%E4%B8%8A%E7%9A%84%E8%8A%82%E7%82%B9%E6%95%B0%E3%80%82%0A%0A%E8%AF%B4%E6%98%8E%3A%20%E5%8F%B6%E5%AD%90%E8%8A%82%E7%82%B9%E6%98%AF%E6%8C%87%E6%B2%A1%E6%9C%89%E5%AD%90%E8%8A%82%E7%82%B9%E7%9A%84%E8%8A%82%E7%82%B9%E3%80%82%0A%60%60%60%0A%20%20%20%203%0A%20%20%20%2F%20%5C%0A%20%209%20%2020%0A%20%20%20%20%2F%20%20%5C%0A%20%20%2015%20%20%207%20%20%20%20%20%20%20%20%20%20%E8%BF%94%E5%9B%9E%E5%AE%83%E7%9A%84%E6%9C%80%E5%A4%A7%E6%B7%B1%E5%BA%A6%203%20%0A%60%60%60%0A%0A%23%23%23%20c%20plus%0A%0A%0A%20%E9%80%92%E5%BD%92%0A%20%20%20%20%0A%20%20%20%20%5B%E9%A2%98%E8%A7%A3%5D(https%3A%2F%2Fleetcode-cn.com%2Fproblems%2Fmaximum-depth-of-binary-tree%2Fsolution%2Fer-cha-shu-de-zui-da-shen-du-by-leetcode%2F)%0A%60%60%60c%0Aclass%20Solution%20%7B%0Apublic%3A%0A%20%20%20%20int%20maxDepth(TreeNode%20root)%20%7B%0A%20%20%20%20%20%20%20%20return%20helper(root)%3B%0A%20%20%20%20%7D%0A%20%20%20%20int%20helper(TreeNode%20node)%20%7B%0A%20%20%20%20%20%20%20%20if%20(node%20%3D%3D%20NULL)%20%20%20return%200%3B%0A%20%20%20%20%20%20%20%20int%20left%20%3D%20helper(node-%3Eleft)%3B%0A%20%20%20%20%20%20%20%20int%20right%20%3D%20helper(node-%3Eright)%3B%0A%20%20%20%20%20%20%20%20return%20max(left%2C%20right)%20%2B%201%3B%0A%20%20%20%20%7D%0A%7D%3B%0A%60%60%60%0A*%0A%0A%23%23%23%20Golang%0A%0A%60%60%60go%0A%0Afunc%20maxDepth(root%20TreeNode)%20int%20%7B%0A%20%20%20%20if%20(root%20%3D%3D%20nil)%7B%0A%20%20%20%20%20%20%20%20return%200%0A%20%20%20%20%7D%0A%20%20%20%20%0A%20%20%20%20ld%20%3A%3D%20maxDepth(root.Left)%0A%20%20%20%20rd%20%3A%3D%20maxDepth(root.Right)%0A%20%20%20%20if%20ld%20%3E%20rd%20%7B%0A%20%20%20%20%20%20%20%20return%20ld%20%2B%201%0A%20%20%20%20%7Delse%7B%0A%20%20%20%20%20%20%20%20return%20rd%20%2B%201%0A%20%20%20%20%7D%0A%7D%0A%60%60%60%0A%0A*