面试题55 - I. 二叉树的深度

image.png

递归

  1. package main
  2. type TreeNode struct {
  3. Val int
  4. Left *TreeNode
  5. Right *TreeNode
  6. }
  7. func Max(a,b int)int {
  8. if a>b{
  9. return a
  10. }
  11. return b
  12. }
  13. func maxDepth(root *TreeNode) int {
  14. if root==nil{
  15. return 0
  16. }
  17. lHeight := maxDepth(root.Left)
  18. rHeight := maxDepth(root.Right)
  19. return Max(lHeight,rHeight)+1
  20. }
  21. func main() {
  22. }

image.png

迭代

  1. func maxDepth(root *TreeNode) int {
  2. if root==nil{
  3. return 0
  4. }
  5. ques := make([]*TreeNode,0)
  6. ques = append(ques,root)
  7. height :=0
  8. for len(ques)!=0{
  9. l :=len(ques)
  10. for i:=0;i<l;i++{
  11. node :=ques[i]
  12. if node.Left!=nil {
  13. ques = append(ques,node.Left)
  14. }
  15. if node.Right!=nil {
  16. ques = append(ques,node.Right)
  17. }
  18. }
  19. ques =ques[l:]
  20. height++
  21. }
  22. return height
  23. }

image.png