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 boolean contains(TreeNode root, TreeNode node) {
- if (root == null) {
- return false;
- }
- if (root.val == node.val) {
- return true;
- }
- return contains(root.left, node) || contains(root.right, node);
- }
- public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
- if (contains(root, p) && contains(root, q)) {
- TreeNode node = lowestCommonAncestor(root.left, p, q);
- if (node == null) {
- node = lowestCommonAncestor(root.right, p, q);
- if (node == null) {
- node = root;
- }
- }
- return root;
- }
- return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment