Java forward recursion method

  • 0
    public class Solution {
        int findpath(TreeNode root, int[] maxpath){
            if(root==null) return 0;
            int mp=1;
            int maxleft = findpath(root.left, maxpath);
            int maxright = findpath(root.right, maxpath);
            if(root.left!=null && root.left.val-1==root.val){
                mp = Math.max(mp, maxleft+1);
            if(root.right!=null && root.right.val-1==root.val){
                mp = Math.max(mp, maxright+1);
            maxpath[0] = Math.max(Math.max(mp, Math.max(maxleft, maxright)),maxpath[0]);
            return mp;
        public int longestConsecutive(TreeNode root) {
            int[] maxpath = new int[1];
            findpath(root, maxpath);
            return maxpath[0];

Log in to reply

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