Advertisement
ogv

Untitled

ogv
Sep 20th, 2019
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.91 KB | None | 0 0
  1. // You are here!  Your runtime beats 100.00 % of java submissions.
  2.  
  3. class Solution {
  4.     TreeNode lca;
  5.    
  6.     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  7.         search(root, p, q, 0);
  8.         return lca;
  9.     }  
  10.    
  11. // govnokod ON
  12.     private int search(TreeNode root, TreeNode p, TreeNode q, int state) {
  13.         int s0, s1;
  14.  
  15.         if (root == p || root == q) {
  16.             state++;
  17.             if (state == 2) return 2;
  18.             lca = root;
  19.         }
  20.         s0 = state;
  21.         if (root.left != null) {
  22.             state = search(root.left, p, q, state);
  23.         }
  24.        
  25.         if (state == 2) return state;
  26.        
  27.         s1= state;
  28.        
  29.         if (root.right != null) {
  30.             state = search(root.right, p, q, state);
  31.         }
  32.        
  33.         if (state == 2 && s0 == 0 && s1 == 1) lca = root;
  34.        
  35.         return state;
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement