| 4 | |
| 5 | public class QuestionCBad { |
| 6 | public static TreeNode commonAncestorBad(TreeNode root, TreeNode p, TreeNode q) { |
| 7 | if (root == null) { |
| 8 | return null; |
| 9 | } |
| 10 | if (root == p && root == q) { |
| 11 | return root; |
| 12 | } |
| 13 | |
| 14 | TreeNode x = commonAncestorBad(root.left, p, q); |
| 15 | if (x != null && x != p && x != q) { // Found common ancestor |
| 16 | return x; |
| 17 | } |
| 18 | |
| 19 | TreeNode y = commonAncestorBad(root.right, p, q); |
| 20 | if (y != null && y != p && y != q) { |
| 21 | return y; |
| 22 | } |
| 23 | |
| 24 | if (x != null && y != null) { |
| 25 | return root; // This is the common ancestor |
| 26 | } else if (root == p || root == q) { |
| 27 | return root; |
| 28 | } else { |
| 29 | return x == null ? y : x; |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | public static void main(String[] args) { |
| 34 | int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; |