Binary Tree Longest Consecutive Sequence -- LeetCode
2016-08-31 08:07
405 查看
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,
Longest consecutive sequence path is
Longest consecutive sequence path is
思路:递归。时间复杂度O(N)。
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 \ 5
Longest consecutive sequence path is
3-4-5, so return
3.
2 \ 3 / 2 / 1
Longest consecutive sequence path is
2-3,not
3-2-1, so return
2.
思路:递归。时间复杂度O(N)。
/** * 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 help(TreeNode *root, int &count) { if (root == NULL) return 0; int leftCount = help(root->left, count); int rightCount = help(root->right, count); int res = 1; if (root->left && root->val + 1 == root->left->val) res = 1 + leftCount; if (root->right && root->val + 1 == root->right->val) res = std::max(res, 1 + rightCount); count = std::max(count, res); return res; } int longestConsecutive(TreeNode* root) { int count = 0; help(root, count); return count; } };
相关文章推荐
- [LeetCode298]Binary Tree Longest Consecutive Sequence
- leetcode 298: Binary Tree Longest Consecutive Sequence
- [leetcode 298] Binary Tree Longest Consecutive Sequence---求二叉树连续序列的长度
- LeetCode- Binary Tree Longest Consecutive Sequence
- Leetcode: Binary Tree Longest Consecutive Sequence
- LeetCode Binary Tree Longest Consecutive Sequence
- [LeetCode]Binary Tree Longest Consecutive Sequence
- [LeetCode] Binary Tree Longest Consecutive Sequence II 二叉树最长连续序列之二
- Leetcode 298 Binary Tree Longest Consecutive Sequence
- [LeetCode] Binary Tree Longest Consecutive Sequence
- Leetcode Binary Tree Longest Consecutive Sequence
- LeetCode "Binary Tree Longest Consecutive Sequence"
- [LeetCode] Binary Tree Longest Consecutive Sequence II 二叉树最长连续序列之二
- Leetcode: Binary Tree Longest Consecutive Sequence
- [LeetCode] Binary Tree Longest Consecutive Sequence 二叉树最长连续序列
- [Leetcode]Binary Tree Longest Consecutive Sequence
- LintCode Binary Tree Longest Consecutive Sequence II
- 298. Binary Tree Longest Consecutive Sequence
- Binary Tree Longest Consecutive Sequence
- 298. Binary Tree Longest Consecutive Sequence