Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for a binary tree node.
- * public class TreeNode {
- * int val;
- * TreeNode left;
- * TreeNode right;
- * TreeNode(int x) { val = x; }
- * }
- */
- public class Solution {
- public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
- if (root == null)
- return null;
- // both p and q are less than root
- // their ancestor must be in root.left
- if (p.val < root.val && q.val < root.val)
- return lowestCommonAncestor(root.left, p, q);
- // both p and q are greater than root
- // their ancestor must be in root.right
- if (p.val > root.val && q.val > root.val)
- return lowestCommonAncestor(root.right, p, q);
- return root;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement