SHARE
TWEET

Untitled

a guest Nov 12th, 2019 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class LongestUnivaluePath {
  2.     public static void main(String args[]) {
  3.         TreeNode root = new TreeNode(5);
  4.         root.left = new TreeNode(1);
  5.         root.left.right = new TreeNode(1);
  6.         root.left.left = new TreeNode(1);
  7.         root.right = new TreeNode(5);
  8.         root.right.right = new TreeNode(5);
  9.         //root.left.right = new TreeNode(3);
  10.         System.out.println(longestUnivaluePath(root));
  11.     }
  12.  
  13.     static int length = 0; // global variable
  14.  
  15.     public static int longestUnivaluePath(TreeNode root) {
  16.         if (root == null) return 0;
  17.         getLen(root, root.val);
  18.         return length;
  19.     }
  20.  
  21.     private static int getLen(TreeNode node, int val) {
  22.         if (node == null) return 0;
  23.         int left = getLen(node.left, node.val);
  24.         int right = getLen(node.right, node.val);
  25.         length = Math.max(length, left + right);
  26.         if (val == node.val) return Math.max(left, right) + 1;
  27.         return 0;
  28.     }
  29.  
  30.  
  31. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top