Leetcode 549. 二叉树中最长的连续序列

226 阅读1分钟

题目地址

解题思路

根据题意,我们得知需求从根节点开始向左右子树递归求解连续的序列,但是连续序列可能是递增的也可能是递减的。所以我们需要使用变量d的值为1或-1来表示递增还是递减序列。
由于我们需要从树的任意节点开始找连续序列,所以需要将左右节点传入longestConsecutive函数中进行递归遍历,实现双重递归遍历。
根据递归三部曲确定cal递归函数
参数与返回值:参数是当前节点的值和d,返回值为当前节点的最长连续序列的长度
结束条件:遍历到叶子结点的时候停止
单层逻辑:判断左右子树是否为空且节点与它左右子树的节点差值是否等于d,如果满足则继续递归。由于连续序列是一条边的长度,所以去左右子树的最大值。

复杂度分析

我理解通过二叉树的根节点进行递归遍历,每个节点都访问一次的时间复杂度是O(N)。那么,每一个节点都递归遍历两遍的时间复杂度是O(N^2)

示例代码

func longestConsecutive(root *TreeNode) int {
   if root == nil {
      return 0
   }
   return max(cal(root, 1)+cal(root, -1)+1,
      max(longestConsecutive(root.Left), longestConsecutive(root.Right)))
}


func cal(n *TreeNode, d int) int {
   if n == nil {
      return 0
   }
   l, r := 0, 0
   if n.Left != nil && n.Val-n.Left.Val == d {
      l = cal(n.Left, d) + 1
   }
   if n.Right != nil && n.Val-n.Right.Val == d {
      r = cal(n.Right, d) + 1
   }
   return max(l, r)
}


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