码迷,mamicode.com
首页 > 其他好文 > 详细

298. Binary Tree Longest Consecutive Sequence

时间:2018-07-22 11:19:50      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:solution   问题   root   Plan   rom   refers   color   代码   efi   

问题描述:

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

标签:solution   问题   root   Plan   rom   refers   color   代码   efi   

原文地址:https://www.cnblogs.com/yaoyudadudu/p/9348953.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!