Easy pre-order traverse solution.


  • 0
    S

    A straight forward pre-order traverse solution.

    public class Solution {
    int res = 1;
    public int longestConsecutive(TreeNode root) {
        if(root == null)
            return 0;
        dfs(root, root.val, 1);
        return res;
    }
    
    public void dfs(TreeNode root, int pre, int count) {
        if(root == null) {
            if(count > res)
                res = count;
            return;
        }
        if(root.val == pre+1) {
            count++;
        }else {
            if(count > res)
                res = count;
            count = 1;
        }
        
        dfs(root.left, root.val, count);
        dfs(root.right, root.val, count);
    }
    

    }


Log in to reply
 

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