|
| 1 | +# Definition for a binary tree node. |
| 2 | +# class TreeNode(object): |
| 3 | +# def __init__(self, x): |
| 4 | +# self.val = x |
| 5 | +# self.left = None |
| 6 | +# self.right = None |
| 7 | + |
| 8 | +# Top-Down approach - Accepted |
| 9 | +class Solution(object): |
| 10 | + def longestConsecutive(self, root): |
| 11 | + """ |
| 12 | + :type root: TreeNode |
| 13 | + :rtype: int |
| 14 | + """ |
| 15 | + # if not root: |
| 16 | + # return 0 |
| 17 | + longestSeque = 0 |
| 18 | + longestSeque = self.longestConsecutiveHelper(root, None, 0, longestSeque) |
| 19 | + return longestSeque |
| 20 | + |
| 21 | + def longestConsecutiveHelper(self, root, parent, currentLongestSeque, longestSeque): |
| 22 | + if not root: |
| 23 | + return max(currentLongestSeque, longestSeque) |
| 24 | + if parent and root.val == parent.val + 1: |
| 25 | + currentLongestSeque += 1 |
| 26 | + else: |
| 27 | + currentLongestSeque = 1 |
| 28 | + longestSeque = max(currentLongestSeque, longestSeque) |
| 29 | + leftLength = self.longestConsecutiveHelper(root.left, root, currentLongestSeque, longestSeque) |
| 30 | + rightLength = self.longestConsecutiveHelper(root.right, root, currentLongestSeque, longestSeque) |
| 31 | + maxLength = max(leftLength, rightLength, longestSeque) |
| 32 | + return maxLength |
| 33 | + |
| 34 | + |
| 35 | + |
| 36 | + |
| 37 | +# Bottom-Up approach - Accepted |
| 38 | +class Solution(object): |
| 39 | + def longestConsecutive(self, root): |
| 40 | + """ |
| 41 | + :type root: TreeNode |
| 42 | + :rtype: int |
| 43 | + """ |
| 44 | + if not root: |
| 45 | + return 0 |
| 46 | + dummyNode = TreeNode(float("inf")) |
| 47 | + dummyNode.left = root |
| 48 | + longestSeque, val = self.longestConsecutiveHelper(dummyNode) |
| 49 | + return longestSeque |
| 50 | + |
| 51 | + def longestConsecutiveHelper(self, root): |
| 52 | + if not root: |
| 53 | + return (0, float("-inf")) |
| 54 | + leftLength, leftVal = self.longestConsecutiveHelper(root.left) |
| 55 | + rightLength, rightVal = self.longestConsecutiveHelper(root.right) |
| 56 | + |
| 57 | + if leftVal != float("-inf") and root.val == leftVal - 1: |
| 58 | + leftLength += 1 |
| 59 | + elif rightVal != float("-inf") and root.val == rightVal - 1: |
| 60 | + rightLength += 1 |
| 61 | + longestSeque = max(leftLength, rightLength, 1) |
| 62 | + |
| 63 | + return (longestSeque, root.val) |
0 commit comments