C# DFS Accepted


  • 0
    S
    public class Solution {
    public int LongestConsecutive(TreeNode root) {
        int[] len = new int[1];
        if(root==null)return 0;
        int v= LongestConsecutive(root,len);
        return v>len[0]?v:len[0];
    }
    //left: max from left branch
    //leftmaxwithroot: max from left branch when using the left root
    //right: max from right branch
    //rightmaxwithroot: max from right branch when using the right root
    public int LongestConsecutive(TreeNode root, int[] len){
        int left=0;
        int leftmaxwithroot=0;
        int right=0;
        int rightmaxwithroot=0;
        if(root.left!=null){
            left=LongestConsecutive(root.left,len);
            leftmaxwithroot=len[0];
        }
        if(root.right!=null){
            right=LongestConsecutive(root.right,len);
            rightmaxwithroot=len[0];
        }
        int maxwithroot=1;
        if(root.left!=null&&(root.val+1)==root.left.val){
            maxwithroot=leftmaxwithroot+1;
        }
        if(root.right!=null&&(root.val+1)==root.right.val){
            maxwithroot=maxwithroot>rightmaxwithroot+1?maxwithroot:rightmaxwithroot+1;
        }
        len[0]=maxwithroot;
        int res= left>right?left:right;
        return res>maxwithroot?res:maxwithroot;
    }
    

    }


Log in to reply
 

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