yerzhik

Вариант 1

Jul 13th, 2015
324
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.94 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. public class Solution {
  11.     public boolean contains(TreeNode root, TreeNode node) {
  12.         if (root == null) {
  13.             return false;
  14.         }
  15.         if (root.val == node.val) {
  16.             return true;
  17.         }
  18.         return contains(root.left, node) || contains(root.right, node);
  19.     }
  20.     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  21.         if (contains(root, p) && contains(root, q)) {
  22.             TreeNode node = lowestCommonAncestor(root.left, p, q);
  23.             if (node == null) {
  24.                 node = lowestCommonAncestor(root.right, p, q);
  25.                 if (node == null) {
  26.                     node = root;
  27.                 }
  28.             }
  29.             return root;
  30.         }
  31.         return null;
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment