[LeetCode298]Binary Tree Longest Consecutive Sequence

来源:互联网 发布:威海近年来人口数据 编辑:程序博客网 时间:2024/04/26 07:34
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).For example,       1        \         3        / \       2   4            \             5Longest consecutive sequence path is 3-4-5, so return 3.       2        \         3        /        2          /      1Longest consecutive sequence path is 2-3,not3-2-1, so return 2.Hide Company Tags GoogleHide Tags TreeHide Similar Problems (H) Longest Consecutive Sequence

我能吐槽一下吗,leetcode更新简直神速,学渣已经要吐血身亡了。。。妈妈救我

好了, 根据题意,满足条件的sequence必须从小到大,321不算。

依旧,binary tree 这种,我们是不是就喜欢用recursion 呢!

/** * 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) {    //     if(!root) return 0;    //     helper(root, 1, root->val+1);    //     return maxLen;    // }    // void helper(TreeNode* node, int len, int target){    //     if(!node) return;    //     if(node->val == target) ++len;    //     else len = 1;    //     maxLen = max(maxLen , len);    //     helper(node->left, len, node->val + 1);    //     helper(node->right, len, node->val + 1);    // }    // private: int maxLen = 0;    int longestConsecutive(TreeNode* root) {        return search(root, nullptr, 0);    }    int search(TreeNode *root, TreeNode *parent, int len) {        if (!root) return len;        len = (parent && root->val == parent->val + 1)?len+1:1;        return max(len, max(search(root->left, root, len), search(root->right, root, len)));    }};
0 0