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

本文探讨了在二叉树中寻找最长连续路径的问题,采用递归加分解的方法,通过全局变量存储最长路径长度,实现从根节点到任意节点的最长连续递增路径的查找。

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

样例

举个例子:

   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;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值