第21天--算法(Leetcode 687)


687.最长同值路径

public int longestUnivaluePath(TreeNode root) {         if(root == null) {             return 0;         }         return process(root).notBeginX - 1;     }     public Info process(TreeNode root) {         if(root == null) {             return new Info(0,0);         }         TreeNode l = root.left;         TreeNode r = root.right;         Info left = process(l);         Info right = process(r);         int beginX;         int notBeginX;         beginX = 1;         if(l != null) {             if(root.val == l.val) {                 beginX = 1 + left.beginX;             }         }         if(r != null) {             if(root.val == r.val) {                 beginX = Math.max(1 + right.beginX,beginX);             }         }         notBeginX = Math.max(beginX,Math.max(left.notBeginX,right.notBeginX));         if(l != null && r != null && root.val == l.val && root.val == r.val) {             notBeginX = Math.max(notBeginX,left.beginX + right.beginX + 1);         }         return new Info(beginX,notBeginX);     } class Info {     int beginX;     int notBeginX;     public Info(int beginX,int notBeginX) {         this.beginX = beginX;         this.notBeginX = notBeginX;     } }