ChiragLulla

Untitled

Jul 22nd, 2022 (edited)
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.35 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.     public List<Integer> search(TreeNode root, TreeNode node) {
  12.         if(root == null) return null;
  13.        
  14.         if(root == node) {
  15.             List<Integer> path = new ArrayList<>();
  16.             path.add(root.val);
  17.             return path;
  18.         }
  19.        
  20.         List<Integer> left = search(root.left, node);
  21.         if(left != null) {
  22.             left.add(root.val);
  23.             return left;
  24.         }
  25.         List<Integer> right = search(root.right, node);
  26.         if(right != null) {
  27.             right.add(root.val);
  28.             return right;
  29.         }
  30.        
  31.         return null;
  32.     }
  33.     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  34.         List<Integer> pathp = search(root, p);
  35.         List<Integer> pathq = search(root, q);
  36.        
  37.         int i = pathp.size()-1, j = pathq.size()-1;
  38.        
  39.         while(i >= 0 && j >= 0) {
  40.             if(pathp.get(i) == pathq.get(j)) {
  41.                 i--; j--;
  42.             }else{
  43.                 break;
  44.             }
  45.         }
  46.        
  47.         // System.out.println(pathp.get(i+1));
  48.        
  49.         return new TreeNode(pathp.get(i+1));
  50.     }
  51. }
Add Comment
Please, Sign In to add comment