Divide and Conquar
class Solution {
private:
int maxNum = INT_MIN;
public:
/*
* @param root: the root of binary tree
* @return: the length of the longest consecutive sequence path
*/
int longestConsecutive(TreeNode * root) {
// write your code here
dfsHelper(root);
return maxNum;
}
int dfsHelper(TreeNode* root) {
if (root == NULL) {
return 0;
}
int left = dfsHelper(root->left);
int right = dfsHelper(root->right);
int localMax = 1;
if (root->left != NULL && root->left->val == root->val + 1) {
localMax = left + 1;
}
if (root->right != NULL && root->right->val == root->val + 1) {
localMax = right + 1;
}
if (localMax > maxNum) {
maxNum = localMax;
}
return localMax;
}
};
DFS
class Solution {
private:
int maxNum = 0;
public:
/*
* @param root: the root of binary tree
* @return: the length of the longest consecutive sequence path
*/
int longestConsecutive(TreeNode * root) {
// write your code here
// int maxNum = 0;
dfsHelper(root, 0, root->val,maxNum);
return maxNum;
}
void dfsHelper(TreeNode* root, int curLength, int expectNum, int& maxNum) {
if (root == NULL) {
return;
}
if (root->val == expectNum) {
cout<<root->val<<expectNum<<endl;
curLength++;
} else {
curLength = 1;
}
maxNum = max(maxNum, curLength);
cout<<maxNum<<endl;
dfsHelper(root->left, curLength, root->val+1, maxNum);
dfsHelper(root->right, curLength, root->val+1, maxNum);
}
};