Advertisement
sweet1cris

Untitled

Feb 9th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.55 KB | None | 0 0
  1.  
  2. /**
  3.  * Definition for a binary tree node.
  4.  * public class TreeNode {
  5.  *     int val;
  6.  *     TreeNode left;
  7.  *     TreeNode right;
  8.  *     TreeNode(int x) { val = x; }
  9.  * }
  10.  */
  11. class ResultType {
  12.     public int max_length, max_down, max_up;
  13.     ResultType(int len, int down, int up) {
  14.         max_length = len;
  15.         max_down = down;
  16.         max_up = up;    
  17.     }
  18. }
  19.  
  20. public class Solution {
  21.     /**
  22.      * @param root the root of binary tree
  23.      * @return the length of the longest consecutive sequence path
  24.      */
  25.     public int longestConsecutive2(TreeNode root) {
  26.         // Write your code here
  27.         return helper(root).max_length;
  28.     }
  29.    
  30.     ResultType helper(TreeNode root) {
  31.         if (root == null) {
  32.             return new ResultType(0, 0, 0);
  33.         }
  34.  
  35.         ResultType left = helper(root.left);
  36.         ResultType right = helper(root.right);
  37.  
  38.         int down = 0, up = 0;
  39.         if (root.left != null && root.left.val + 1 == root.val)
  40.             down = Math.max(down, left.max_down + 1);
  41.  
  42.         if (root.left != null && root.left.val - 1 == root.val)
  43.             up = Math.max(up, left.max_up + 1);
  44.  
  45.         if (root.right != null && root.right.val + 1 == root.val)
  46.             down = Math.max(down, right.max_down + 1);
  47.  
  48.         if (root.right != null && root.right.val - 1 == root.val)
  49.             up = Math.max(up, right.max_up + 1);
  50.  
  51.         int len = down + 1 + up;
  52.         len = Math.max(len, Math.max(left.max_length, right.max_length));
  53.  
  54.         return new ResultType(len, down, up);
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement