298 Binary Tree Longest Consecutive Sequence

298. Binary Tree Longest Consecutive Sequence

1. Question

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 is3-4-5, so return3.

   2
    \
     3
    / 
   2    
  / 
 1

Longest consecutive sequence path is2-3,not3-2-1, so return2.

2. Implementation

(1) DFS

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int longestConsecutive(TreeNode root) {
        if (root == null) {
            return 0;
        }

        int[] maxLen = new int[1];
        getLongestConsecutive(root, root.val + 1, 1, maxLen);
        return maxLen[0];
    }

    public void getLongestConsecutive(TreeNode node, int target, int curLen, int[] maxLen) {
        if (node == null) {
            return;
        }

        if (node.val == target) {
            ++curLen;
        }
        else {
            curLen = 1;
        }

        maxLen[0] = Math.max(maxLen[0], curLen);

        getLongestConsecutive(node.left, node.val + 1, curLen, maxLen);
        getLongestConsecutive(node.right, node.val + 1, curLen, maxLen);
    }
}

(2) BFS

class Solution {
    public int longestConsecutive(TreeNode root) {
        if (root == null) {
            return 0;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        Queue<Integer> len = new LinkedList<>();

        queue.add(root);
        len.add(1);
        int maxLen = 1;

        while (!queue.isEmpty()) {
            int size = queue.size();

            for (int i = 0; i < size; i++) {
                TreeNode curNode = queue.remove();
                int curLen = len.remove();

                maxLen = Math.max(maxLen, curLen);

                if (curNode.left != null) {
                    queue.add(curNode.left);
                    len.add(curNode.left.val == curNode.val + 1 ? curLen + 1 : 1);
                }

                if (curNode.right != null) {
                    queue.add(curNode.right);
                    len.add(curNode.right.val == curNode.val + 1 ? curLen + 1 : 1);
                }
            }
        }
        return maxLen;
    }
}

3. Time & Space Complexity

DFS: 时间复杂度: O(n), 空间复杂度: O(h)

BFS: 时间复杂度: O(n), 空间复杂度: O(w), w为树中拥有最多node的一层的node个数

Last updated