298. Binary Tree Longest Consecutive Sequence

Posted yaoyudadudu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }
};

 

以上是关于298. Binary Tree Longest Consecutive Sequence的主要内容,如果未能解决你的问题,请参考以下文章

298. Binary Tree Longest Consecutive Sequence

[LC] 298. Binary Tree Longest Consecutive Sequence

298.Binary Tree Longest Consecutive Sequence

[Locked] Binary Tree Longest Consecutive Sequence

Binary Tree Longest Consecutive Sequence

LeetCode - Binary Tree Longest Consecutive Sequence