zoukankan      html  css  js  c++  java
  • LeetCode- 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.

    Solution:

     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     public class ConsLen {
    12         int fromMe;
    13         int fromBelow;
    14 
    15         public ConsLen(int m, int b){
    16             fromMe = m;
    17             fromBelow = b;
    18         }
    19     }
    20 
    21     public int longestConsecutive(TreeNode root) {
    22         if (root==null) return 0;
    23             
    24         ConsLen res = findConsecutiveSeq(root);
    25 
    26         return Math.max(res.fromMe,res.fromBelow);
    27     }
    28 
    29     public ConsLen findConsecutiveSeq(TreeNode cur){
    30         if (cur.left==null && cur.right==null){
    31             return new ConsLen(1,0);
    32         }
    33 
    34         ConsLen res = new ConsLen(1,0);
    35         if (cur.left!=null){
    36             ConsLen leftRes = findConsecutiveSeq(cur.left);
    37             if (cur.left.val == cur.val+1){
    38                 res.fromMe = leftRes.fromMe + 1;
    39             }
    40             res.fromBelow = Math.max(leftRes.fromMe, leftRes.fromBelow);
    41         }
    42 
    43         if (cur.right!=null){
    44             ConsLen rightRes = findConsecutiveSeq(cur.right);
    45             if (cur.right.val == cur.val+1){
    46                 res.fromMe = Math.max(res.fromMe,rightRes.fromMe+1);
    47             }    
    48             res.fromBelow = Math.max(res.fromBelow,Math.max(rightRes.fromMe,rightRes.fromBelow));
    49         }
    50         
    51         return res;
    52     }
    53 }
  • 相关阅读:
    Linux cron
    web报表工具FineReport常用函数的用法总结(文本函数)
    web报表工具FineReport常用函数的用法总结(文本函数)
    oracle instr函数
    死锁的例子和 synchronized 嵌套使用
    死锁的例子和 synchronized 嵌套使用
    Perl 监控批量错误
    Linux以百万兆字节显示内存大小
    Linux以GB显示内存大小
    Linux以KB显示内存大小
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5792744.html
Copyright © 2011-2022 走看看