1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
binary-tree-longest-consecutive-sequence.cpp 1.03 KB
一键复制 编辑 原始数据 按行查看 历史
// Time: O(n)
// Space: O(h)
/**
* 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 max_len = 0;
longestConsecutiveHelper(root, &max_len);
return max_len;
}
int longestConsecutiveHelper(TreeNode *root, int *max_len) {
if (!root) {
return 0;
}
const int left_len = longestConsecutiveHelper(root->left, max_len);
const int right_len = longestConsecutiveHelper(root->right, max_len);
int cur_len = 1;
if (root->left && root->left->val == root->val + 1) {
cur_len = max(cur_len, left_len + 1);
}
if (root->right && root->right->val == root->val + 1) {
cur_len = max(cur_len, right_len + 1);
}
*max_len = max(*max_len, max(cur_len, max(left_len, right_len)));
return cur_len;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuhang2__2/LeetCode-Solutions.git
git@gitee.com:yuhang2__2/LeetCode-Solutions.git
yuhang2__2
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助