天天看點

LeetCode 298. Binary Tree Longest Consecutive Sequence(二叉樹最長連續序列)

原題網址:https://leetcode.com/problems/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

,not

3-2-1

, so return 

2

.

方法:遞歸周遊,遞歸函數傳入父節點的值,以幫助子節點判斷是否連續。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private int max = 0;
    private void find(TreeNode root, int parent, int count) {
        if (root.val == parent+1) count ++; else count = 1;
        max = Math.max(max, count);
        if (root.left != null) find(root.left, root.val, count);
        if (root.right != null) find(root.right, root.val, count);
    }
    public int longestConsecutive(TreeNode root) {
        if (root == null) return 0;
        max = 1;
        if (root.left != null) find(root.left, root.val, 1);
        if (root.right != null) find(root.right, root.val, 1);
        return max;
    }
}
           

優化:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private int max = 1;
    private void find(TreeNode root, int prev, int len) {
        if (prev+1 == root.val) len ++; else len = 1;
        max = Math.max(max, len);
        if (root.left != null) find(root.left, root.val, len);
        if (root.right != null) find(root.right, root.val, len);
    }
    public int longestConsecutive(TreeNode root) {
        if (root == null) return 0;
        find(root, 0, 0);
        return max;
    }
}