代码随想录算法训练营第14天 | lc104、lc111、lc222

发布时间 2024-01-01 00:23:21作者: geJoyo

(本合集全部为Go语言实现)

相关文章链接:104题解 111题解 222题解
相关视频链接:

Leetcode104

状态:这种简便的写法一开始忘了,看了题解才想到
实现过程中的难点:需要首先明确最终答案的得出是模拟了那种遍历方式

个人写法

func maxDepth(root *TreeNode) int {
  if root == nil {
    return 0
  }
  return int(math.Max(float64(maxDepth(root.Left)), float64(maxDepth(root.Right)))) + 1
}

Leetcode111

状态:
实现过程中的难点:需要明确左右孩子都为空的时候才算是到头

个人写法

func min(i1, i2 int) int {
  if i1 < i2 {
    return i1
  }
  return i2
}

func minDepth(root *TreeNode) int {
  if root == nil {
    return 0
  }
  return minDepth0(root)
}

func minDepth0(root *TreeNode) int {
  if root.Left == nil && root.Right == nil {
    return 1
  } else if root.Left == nil && root.Right != nil {
    return minDepth(root.Right) + 1
  } else if root.Left != nil && root.Right == nil {
    return minDepth(root.Left) + 1
  } else {
    return min(minDepth0(root.Left), minDepth0(root.Right)) + 1
  }
}

Leetcode222

状态:
实现过程中的难点:

个人写法

func countNodes(root *TreeNode) int {
  if root == nil {
    return 0
  }
  return countNodes(root.Left) + countNodes(root.Right) + 1
}

今日收获

  • 了解了树的遍历变种题目的基本思路,首先还是应该确定该题的目标是由那种遍历方式模拟得到的

学习时长:2小时左右