【多次过】Lintcode 595. 二叉树最长连续序列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/85230168

给一棵二叉树,找到最长连续路径的长度。
这条路径是指 任何的节点序列中的起始节点到树中的任一节点都必须遵循 父-子 联系。最长的连续路径必须是从父亲节点到孩子节点(不能逆序)。

样例

举个例子:

   1
    \
     3
    / \
   2   4
        \
         5

最长的连续路径为 3-4-5,所以返回 3

   2
    \
     3
    / 
   2    
  / 
 1

最长的连续路径为 2-3 ,而不是 3-2-1 ,所以返回 2


解题思路:

Traverse + Divide Conquer。用全局变量longest来存储最长长度。

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: the root of binary tree
     * @return: the length of the longest consecutive sequence path
     */
    public int longestConsecutive(TreeNode root) {
        // write your code here
        longest = 0;
        
        helper(root);
        
        return longest;
    }
    
    private int longest;
    
    //返回当前root最长连续路径长度
    private int helper(TreeNode root){
        if(root == null)
            return 0;
        
        //Divide
        int left = helper(root.left);
        int right = helper(root.right);
        
        int tempMax = 1;// at least we have root
        if(root.left != null && root.val+1 == root.left.val){
            tempMax = Math.max(tempMax, left+1);
        }
        
        if(root.right != null && root.val+1 == root.right.val){
            tempMax = Math.max(tempMax, right+1);
        }
        
        longest = Math.max(tempMax, longest);
        
        return tempMax;
    }
}

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/85230168
今日推荐