Advertisement
ChiragLulla

Untitled

Jul 22nd, 2022
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.54 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * public class TreeNode {
  4.  *     int val;
  5.  *     TreeNode left;
  6.  *     TreeNode right;
  7.  *     TreeNode(int x) { val = x; }
  8.  * }
  9.  */
  10. class Solution {
  11.     // search
  12.         // search in a binary tree
  13.         // array of size 2, p -- 1,2 q -- 1,2
  14.         // p - 1, q - 2 stop
  15.         // p - 1, q - 1 left
  16.         // p - 2, q - 2 right
  17.    
  18.     public int search(TreeNode root, TreeNode node) {
  19.         if(root == null) return 0;
  20.        
  21.         if(root == node) return 1;
  22.        
  23.         int left = search(root.left, node);
  24.         if(left == 1) return left;
  25.         int right = search(root.right, node);
  26.         if(right == 1) return right;
  27.        
  28.         return 2;
  29.     }
  30.    
  31.     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  32.         if(root == null) {
  33.             return root;
  34.         }
  35.        
  36.         if(root == p) {
  37.             return p;
  38.         }
  39.         if(root == q) {
  40.             return q;
  41.         }
  42.        
  43.         int dirp = search(root.left, p);
  44.         int dirq = search(root.left, q);
  45.        
  46.         System.out.println(dirp + " " + dirq);
  47.        
  48.         if((dirp == 1 && dirq == 2) || (dirp == 2 && dirq == 1)) {
  49.             return root;
  50.         }
  51.        
  52.         if(dirp == 1 && dirp == 1) {
  53.             return lowestCommonAncestor(root.left, p, q);
  54.         }
  55.        
  56.         if(dirp == 2 && dirp == 2) {
  57.             return lowestCommonAncestor(root.right, p, q);
  58.         }
  59.        
  60.         return null;
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement