Leetcode 298. 二叉树最长连续序列

249 阅读1分钟

题目连接

解题思路

本题要求我们找出二叉树中最长的连续序列,可以分为两步做:
1. 通过深度遍历将二叉树中所有的路径保存下来
2. 根据题意逆序遍历这些路径,并且找到最大值

示例代码

func longestConsecutive(root *TreeNode) int {
   if root == nil {
      return 0
   }
   var dfs func(node *TreeNode, line []int)
   lines := [][]int{}

   dfs = func(node *TreeNode, line []int) {
      if node == nil {
         return
      }
      if node.Left == nil && node.Right == nil {
         line = append(line, node.Val)
         r := make([]int, len(line))
         copy(r, line)
         lines = append(lines, r)
         return
      }
      line = append(line, node.Val)

      dfs(node.Left, line)
      dfs(node.Right, line)
   }

   dfs(root, []int{})

   depth := math.MinInt64

   for i := 0; i < len(lines); i++ {
      line := lines[i]
      var curDepth int
      for j := len(line) - 1; j >= 1; j-- {
         if line[j]-line[j-1] == 1 {
            curDepth += 1
         } else {
            curDepth = 0
         }
         depth = max(depth, curDepth)
      }
   }

   if len(lines) == 1 {
      if len(lines[0]) == 1 {
         return 1
      }
   }

   return depth + 1
}

func max(a, b int) int {
   if a > b {
      return a
   } else {
      return b
   }
}