• LeetCode 549. Binary Tree Longest Consecutive Sequence II


    原题链接在这里:https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/description/

    题目:

    Given a binary tree, you need to find the length of Longest Consecutive Path in Binary Tree.

    Especially, this path can be either increasing or decreasing. For example, [1,2,3,4] and [4,3,2,1] are both considered valid, but the path [1,2,4,3] is not valid. On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order.

    Example 1:

    Input:
            1
           / 
          2   3
    Output: 2
    Explanation: The longest consecutive path is [1, 2] or [2, 1].

    Example 2:

    Input:
            2
           / 
          1   3
    Output: 3
    Explanation: The longest consecutive path is [1, 2, 3] or [3, 2, 1].

    Note: All the values of tree nodes are in the range of [-1e7, 1e7].

    题解:

    Binary Tree Longest Consecutive Sequence类似. 

    采用bottom-up的方法dfs. 每个点同时维护能向下延展的最大increasing 和 decreasing长度.

    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 class Solution {
    11     int max = 0;
    12     public int longestConsecutive(TreeNode root) {
    13         dfs(root);
    14         return max;
    15     }
    16     
    17     private int[] dfs(TreeNode root){
    18         if(root == null){
    19             return new int[2];
    20         }
    21         
    22         int inc = 1;
    23         int dec = 1;
    24         int [] l = dfs(root.left);
    25         int [] r = dfs(root.right);
    26         if(root.left != null){
    27             if(root.left.val - 1 == root.val){
    28                 inc = Math.max(inc, l[0]+1);
    29             }
    30             if(root.left.val + 1 == root.val){
    31                 dec = Math.max(dec, l[1]+1);
    32             }
    33         }
    34         
    35         if(root.right != null){
    36             if(root.right.val - 1 == root.val){
    37                 inc = Math.max(inc, r[0]+1);
    38             }
    39             if(root.right.val + 1 == root.val){
    40                 dec = Math.max(dec, r[1]+1);
    41             }
    42         }
    43         
    44         max = Math.max(max, dec+inc-1);
    45         return new int[]{inc, dec};
    46     }
    47 }
  • 相关阅读:
    插入排序
    排序算法结构表
    两个数字交换的四种方法
    LRU算法实现
    虚拟用户的配置
    【转】Linux查看CPU和内存使用情况
    Linux 多线程开发
    【转】RTSP流理解
    【转】DynDNS使用随笔
    【转】使用 udev 高效、动态地管理 Linux 设备文件
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/8390390.html
Copyright © 2020-2023  润新知