LintCode 595. 二叉树最长连续序列

给一棵二叉树,找到最长连续路径的长度。
这条路径是指 任何的节点序列中的起始节点到树中的任一节点都必须遵循 父-子 联系。最长的连续路径必须是从父亲节点到孩子节点(不能逆序)。

样例
举个例子:

1
    \
  3
    /   \
   2     4
    \
      5
最长的连续路径为 3-4-5,所以返回 3。

   2
      \
     3
       /
   2
   /
1
最长的连续路径为 2-3 ,而不是 3-2-1 ,所以返回 2。

思路:递归计算最长的连续序列,若不连续则把长度重置为1继续递归

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: the root of binary tree
     * @return: the length of the longest consecutive sequence path
     */
    int longestConsecutive(TreeNode * root) {
        // write your code here
        if(root == nullptr) return 0;
        longestPath(root,1);
        return longest;
    }
    
    void longestPath(TreeNode * root,int length){
        longest = max(length,longest);//更新最长长度
        if(root->left){//存在左子树
            if(root->left ->val == root->val + 1) longestPath(root->left,length+1);//连续,继续加1搜索
            else longestPath(root->left,1);//不连续,长度重置为1搜索
        }
        if(root->right){//右子树
            if(root->right->val == root->val + 1) longestPath(root->right,length+1);
            else longestPath(root->right,1);
        }
    }
private:
    int longest = 0;
};

  

posted @ 2018-04-11 17:32  J1ac  阅读(232)  评论(0编辑  收藏  举报