Binary Tree Longest Consecutive Sequence

Given a binary tree, find the length of the longest consecutive sequence path.

The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).

For example, 1 \ 3 / \ 2 4 \ 5 Longest consecutive sequence path is 3-4-5, so return 3. 2 \ 3 / 2
/ 1 Longest consecutive sequence path is 2-3,not3-2-1, so return 2.

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

from Queue import Queue
import sys
class Solution(object):
    def longestConsecutive(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0
        if root.right == None and root.left == None:
            return 1
        else:
            max_size = 1
            size_q = Queue()
            node_q = Queue()
            node_q.put(root)
            size_q.put(1)
            while node_q.empty() == False:
                curr_node = node_q.get()
                curr_size = size_q.get()

                if curr_node.left:
                    left_size = curr_size
                    if curr_node.val == curr_node.left.val - 1:
                        left_size += 1
                        max_size = max(max_size, left_size)
                    else:
                        left_size = 1

                    node_q.put(curr_node.left)
                    size_q.put(left_size)

                if curr_node.right:
                    right_size = curr_size
                    if curr_node.val == curr_node.right.val - 1:
                        right_size += 1
                        max_size = max(max_size, right_size)
                    else:
                        right_size = 1

                    node_q.put(curr_node.right)
                    size_q.put(right_size)

            return max_size

results matching ""

    No results matching ""