题目:
Given a binary tree, you need to find the length of Longest Consecutive Path in Binary Tree.
Especially, this path can be either increasing or decreasing. For example, [1,2,3,4] and [4,3,2,1] are both considered valid, but the path [1,2,4,3] is not valid. On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order.
Example 1:
Input: 1 / 2 3 Output: 2 Explanation: The longest consecutive path is [1, 2] or [2, 1].
Example 2:
Input: 2 / 1 3 Output: 3 Explanation: The longest consecutive path is [1, 2, 3] or [3, 2, 1].
Note: All the values of tree nodes are in the range of [-1e7, 1e7].
链接:https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/#/description
5/10/2017
算法班,自己有思路,但是没有做出来,不知道是思路问题还是代码问题
注意问题:
1. 多个返回值需要判断,可以返回int array或者object
2. main function里不要重复定义maxLength
3. 第29,33行的判断需要把左右的都包括进去,不要覆盖了来自于left的最大值。或者第18,21行用同样的计算来统一。
4. 宁可把当前层的变量和返回值分开,不要随便合起来用,思路容易混。
这个解法是Bottom up,时间复杂度O(n),也是post-order traversal。
思考:是否post-order traversal的做法就是bottom up呢?应该是的吧
这种post-order traversal步骤:
1. 判断特殊null情况
2. 左右子树调用,并返回值
3. 做当前层的判断处理。
1 public class Solution { 2 int maxLength = 0; 3 public int longestConsecutive(TreeNode root) { 4 if (root == null) return 0; 5 longestPath(root); 6 return maxLength; 7 } 8 private int[] longestPath(TreeNode root) { 9 if (root == null) { 10 // return type [increase, decrease] 11 return new int[]{0,0}; 12 } 13 int tmpIncrease = 1, tmpDecrease = 1; 14 if (root.left != null) { 15 int[] leftFlags = longestPath(root.left); 16 if (root.val + 1 == root.left.val) { 17 // increase 18 tmpIncrease = leftFlags[0] + 1; 19 } else if (root.val - 1 == root.left.val) { 20 // decrease 21 tmpDecrease = leftFlags[1] + 1; 22 } 23 } 24 if (root.right != null) { 25 int[] rightFlags = longestPath(root.right); 26 if (root.val + 1 == root.right.val) { 27 // increase 28 // do not override left part max value 29 tmpIncrease = Math.max(rightFlags[0] + 1, tmpIncrease); 30 } else if (root.val - 1 == root.right.val) { 31 // decrease 32 // do not override left part max value 33 tmpDecrease = Math.max(rightFlags[1] + 1, tmpDecrease); 34 } 35 } 36 maxLength = Math.max(tmpIncrease + tmpDecrease - 1, maxLength); 37 return new int[]{tmpIncrease, tmpDecrease}; 38 } 39 }
参考链接:
https://discuss.leetcode.com/topic/85764/neat-java-solution-single-pass-o-n
https://discuss.leetcode.com/topic/85745/java-solution-binary-tree-post-order-traversal
更多讨论:
https://discuss.leetcode.com/category/705/binary-tree-longest-consecutive-sequence-ii