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

    Example 1:

    Input:
    
       1
        
         3
        / 
       2   4
            
             5
    
    Output: 3
    
    Explanation: Longest consecutive sequence path is 3-4-5, so return 3.

    Example 2:

    Input:
    
       2
        
         3
        / 
       2    
      / 
     1
    
    Output: 2 
    
    Explanation: Longest consecutive sequence path is 2-3, not 3-2-1, so return 2.

    解题思路:

    可以用递归的方式来解答,要遍历所有节点,需要一个参数存储当前最长的路径的长度。

    代码:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int longestConsecutive(TreeNode* root) {
            int ret = 0;
            traverse(root, ret);
            return ret;
        }
        int traverse(TreeNode* root, int &ret){
            if(!root) return 0;
            int left = 0, right = 0;
            
            if(root->left){
                left = traverse(root->left, ret);
                if(root->val - root->left->val != -1) left = 0;
            }
            if(root->right){
                right = traverse(root->right, ret);
                if(root->val - root->right->val != -1) right = 0;
            }
            int longest = max(left, right)+1;
            ret = max(ret, longest);
            return longest;
        }
    };
  • 相关阅读:
    02-Java 数组和排序算法
    Spring Security 入门
    mysql外键理解
    redis能否对set数据的每个member设置过期时间
    Redis sortedset实现元素自动过期
    mysql之触发器trigger
    一篇很棒的 MySQL 触发器学习教程
    mysql触发器
    云游戏
    mysql触发器个人实战
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9348953.html
Copyright © 2011-2022 走看看