题目:
Given a binary tree, you need to find the length of Longest Consecutive Path in Binary Tree.
Especially, this path can be either increasing or decreasing. For example, [1,2,3,4] and [4,3,2,1] are both considered valid, but the path [1,2,4,3] is not valid. On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order.
Example 1:
Input: 1 / \ 2 3 Output: 2 Explanation: The longest consecutive path is [1, 2] or [2, 1].
Example 2:
Input: 2 / \ 1 3 Output: 3 Explanation: The longest consecutive path is [1, 2, 3] or [3, 2, 1].
Note: All the values of tree nodes are in the range of [-1e7, 1e7].
思路:
对于以root为根的树来说,符合条件的path可以分为两类:一类是不经过root的,一类是经过root的。不经过root的可以直接通过对其左子树和右子树的递归调用获得。经过root的有两种:一种是在其左子树上由下到上连续递增到root之后,在其右子树上由上到下连续递增;一种是在其左子树上由下到上连续递减到root之后,在其右子树上由上到下继续连续递减。我们取所有可能类型的path的最长长度即可。
代码:
/**
* 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 == NULL) {
return 0;
}
// calculate the paths that go through the root
int l1 = findPath(root->left, root->val, -1) + findPath(root->right, root->val, 1) + 1;
int l2 = findPath(root->left, root->val, 1) + findPath(root->right, root->val, -1) + 1;
int cur = max(l1, l2);
// calcualte the paths that do not go through the root
int childMax = max(longestConsecutive(root->left), longestConsecutive(root->right));
return max(cur, childMax);
}
private:
int findPath(TreeNode* root, int prevVal, int diff){
if(root == NULL) {
return 0;
}
if(root->val == (prevVal + diff)) {
int left = findPath(root->left, root->val, diff);
int right = findPath(root->right, root->val, diff);
return max(left, right) + 1;
}
else {
return 0;
}
}
};