链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
如果我们已经二叉树的左子树和右子树的深度,那么二叉树的最大深度为 max(left,right)+1,同时左子树和右子树的最大深度可以用递归的方式进行计算。
假设我们有一颗二叉树,如下:
3
/ \
9 20
/ \
15 7
通过以上计算,我们就可以找到二叉树的最大深度。
时间复杂度:O(n),因为每个结点只访问一次。
空间复杂度:在最糟糕的情况下,树是完全不平衡的,例如每个结点只剩下左子结点,递归将会被调用 n 次(树的高度),因此保持调用栈的存储将是 O(n)。但在最好的情况下(树是完全平衡的),树的高度将是 log(n),在这种情况下的空间复杂度将是 O(log(n))。
Python:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
return max(self.maxDepth(root.left),self.maxDepth(root.right))+1
Go:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func maxDepth(root *TreeNode) int {
if root == nil{
return 0
}
return max(maxDepth(root.Left),maxDepth(root.Right))+1
}
func max(a,b int) int{
if a>b{
return a
}
return b
}
我们维护一个栈或者队列,来存储当前节点和其深度,然后对二叉树进行一层一层的遍历,直到找到最大深度。
时间复杂度:O(n)
空间复杂度:O(n)
Python:
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root is None:
return 0
stack=[(1,root)]
depth=0
while stack:
curr,root=stack.pop()
if root:
depth=max(depth,curr)
stack.append((curr+1,root.left))
stack.append((curr+1,root.right))
return depth
Go:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func maxDepth(root *TreeNode) int {
if root == nil{
return 0
}
queue := []*TreeNode{root}
depth := 0
for len(queue) > 0{
length := len(queue)
for length > 0{
node := queue[0]
queue =queue[1:]
if node.Left != nil{
queue = append(queue,node.Left)
}
if node.Right != nil{
queue = append(queue,node.Right)
}
length--
}
depth++
}
return depth
}
如果觉得文章不错,希望大家可以扫描上方名片关注我的微信公众号噢,点赞、收藏、在看、分享就再好不过了。如果有任何建议和问题,可以在下方给我留言,我会及时回复的,同时会不定期更新更多的文章,祝我们终将自由。