问题描述:
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).
Example 1:
Input: 1 3 / 2 4 5 Output:3
Explanation: Longest consecutive sequence path is3-4-5
, so return3
.
Example 2:
Input: 2 3 / 2 / 1 Output: 2 Explanation: Longest consecutive sequence path is2-3
, not3-2-1
, so return2
.
解题思路:
可以用递归的方式来解答,要遍历所有节点,需要一个参数存储当前最长的路径的长度。
代码:
/** * 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 ret = 0; traverse(root, ret); return ret; } int traverse(TreeNode* root, int &ret){ if(!root) return 0; int left = 0, right = 0; if(root->left){ left = traverse(root->left, ret); if(root->val - root->left->val != -1) left = 0; } if(root->right){ right = traverse(root->right, ret); if(root->val - root->right->val != -1) right = 0; } int longest = max(left, right)+1; ret = max(ret, longest); return longest; } };