Advertisement
ogv

Untitled

ogv
Sep 20th, 2019
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 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. TreeNode lca;
  12.  
  13. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  14. search(root, p, q, 0);
  15. return lca;
  16. }
  17.  
  18. private int search(TreeNode root, TreeNode p, TreeNode q, int state) {
  19. System.out.println("going " + root.val + " state " + state);
  20. if (root == p) {
  21. System.out.println("found p");
  22. state &= 1;
  23. }
  24. else if (root == q) {
  25. System.out.println("found q");
  26. state &= 2;
  27. }
  28. if (state != 3 && root.left != null) {
  29. System.out.println("go left " + root.left.val);
  30. state &= search(root.left, p, q, state);
  31. }
  32.  
  33. if (state != 3 && root.right != null) {
  34. System.out.println("go right " + root.right.val);
  35. state &= search(root.right, p, q, state);
  36. }
  37.  
  38. if (state == 3) {
  39. lca = root;
  40. }
  41.  
  42. return state;
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement