Skip to content

Commit

Permalink
Implement and test longest consecutive sequence algorithm for binary …
Browse files Browse the repository at this point in the history
…trees
  • Loading branch information
staging-devin-ai-integration[bot] committed Aug 22, 2024
1 parent 8125338 commit 4a3ab9d
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 14 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
maxlen = 0


class Node:
def __init__(self, val=None):
self.left = None
Expand All @@ -15,21 +12,22 @@ def longest_consecutive(root):
"""
if not root:
return 0
DFS(root, 0, root.val)
return maxlen
return DFS(root, None, 0)


def DFS(root, cur, target):
global maxlen
def DFS(root, parent, length):
if not root:
return
if root.val == target:
cur += 1
return length

if parent and root.val == parent.val + 1:
length += 1
else:
cur = 1
maxlen = max(cur, maxlen)
DFS(root.left, cur, root.val + 1)
DFS(root.right, cur, root.val + 1)
length = 1

left_length = DFS(root.left, root, length)
right_length = DFS(root.right, root, length)

return max(length, left_length, right_length)


if __name__ == '__main__':
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import unittest
from longest_consecutive_sequence import Node, longest_consecutive

class TestLongestConsecutiveSequence(unittest.TestCase):
def test_example_case(self):
root = Node(1)
root.right = Node(3)
root.right.left = Node(2)
root.right.right = Node(4)
root.right.right.right = Node(5)
self.assertEqual(longest_consecutive(root), 3)

def test_empty_tree(self):
self.assertEqual(longest_consecutive(None), 0)

def test_single_node(self):
root = Node(1)
self.assertEqual(longest_consecutive(root), 1)

def test_no_consecutive_sequence(self):
root = Node(1)
root.left = Node(3)
root.right = Node(5)
self.assertEqual(longest_consecutive(root), 1)

def test_multiple_consecutive_sequences(self):
root = Node(1)
root.left = Node(2)
root.left.left = Node(3)
root.right = Node(4)
root.right.right = Node(5)
root.right.right.right = Node(6)
self.assertEqual(longest_consecutive(root), 3)

if __name__ == '__main__':
unittest.main()

0 comments on commit 4a3ab9d

Please sign in to comment.