描述
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明:叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
1. 递归 先求出左右子树的高度, 再返回左右子树最高+1
2. 非递归算法 利用层级遍历 在遍历完每一层时层数+1
实现
func MaxDepth(root *TreeNode) int {
if root == nil{
return 0
}
r := MaxDepth(root.Right)
l := MaxDepth(root.Left)
return Max(r, l) + 1
}
func MaxDepthBfs(root *TreeNode) int {
var depth int
if root == nil{
return depth
}
stack := make([]*TreeNode, 0)
stack = append(stack, root)
for len(stack) > 0{
depth++
tmpStack := make([]*TreeNode, 0)
for len(stack) > 0{
top := stack[len(stack) - 1]
stack = stack[0:len(stack) - 1]
if top.Left != nil{
tmpStack = append(tmpStack, top.Left)
}
if top.Right != nil{
tmpStack = append(tmpStack, top.Right)
}
}
stack = stack[0:0]
stack = append(stack, tmpStack...)
}
return depth
}