One post order traversal solution

  • 0

    use a global variable to keep track of current max length. I think the code is self explaining.

    class Solution {
    int longestConsecutive(TreeNode* root) {
    int count=0;
    if(root==NULL) return 0;
    return count;

    int lc(TreeNode* root,int& count){
        int leftCount=0,rightCount=0;
        int res=1;
        if(root->left) leftCount = lc(root->left,count);
        if(root->right) rightCount = lc(root->right,count);
        if(root->left && root->val == root->left->val-1) res = max(res,1+leftCount);
        if(root->right && root->val == root->right->val-1) res = max(res,1+rightCount);
        if(res>count) count = res;
        return res;


Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.