LeetCode 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,not3-2-1, so return 2.

题解:

DFS向下走. 采用up-bottom的方法. 需要记录上一个点的值时在recursion 过程中加上pre这个parameter.

Time Complexity: O(n). Space: O(logn).

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     private int max = 0; 
12     public int longestConsecutive(TreeNode root) {
13         if(root == null){
14             return max;
15         }
16         findLongest(root, 0, root);
17         return max;
18     }
19     //由上到下
20     private void findLongest(TreeNode root, int curMax, TreeNode pre){
21         if(root == null){
22             return;
23         }
24         if(root.val == pre.val + 1){
25             curMax++;
26         }else{
27             curMax = 1;
28         }
29         max = Math.max(max, curMax);
30         
31         findLongest(root.left, curMax, root);
32         findLongest(root.right, curMax, root);
33     }
34 }

类似Longest Consecutive Sequence.

你可能感兴趣的:(LeetCode Binary Tree Longest Consecutive Sequence)