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;
        }
    };
  • 相关阅读:
    JDK1.0-缓冲流
    笔试错误1
    JVM 垃圾收集(转)
    Trie树和后缀树(转,简化)
    海量数据处理(转,简化)
    Struts2 内核之我见(转) -(主要是拦截器链和过滤链介绍和源码及其设计模式)
    phpize增加php模块
    Ubuntu下SVN安装和配置
    Linux下SVN配置hook经验总结
    Kruakal 算法——练习总结
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9348953.html
Copyright © 2011-2022 走看看