|
| 1 | +/* |
| 2 | + * @lc app=leetcode.cn id=236 lang=java |
| 3 | + * |
| 4 | + * [236] 二叉树的最近公共祖先 |
| 5 | + */ |
| 6 | + |
| 7 | +// @lc code=start |
| 8 | +/** |
| 9 | + * Definition for a binary tree node. |
| 10 | + * public class TreeNode { |
| 11 | + * int val; |
| 12 | + * TreeNode left; |
| 13 | + * TreeNode right; |
| 14 | + * TreeNode(int x) { val = x; } |
| 15 | + * } |
| 16 | + */ |
| 17 | +class Solution { |
| 18 | + |
| 19 | + private TreeNode ans; |
| 20 | + |
| 21 | + public Solution() { |
| 22 | + // Variable to store LCA node. |
| 23 | + this.ans = null; |
| 24 | + } |
| 25 | + |
| 26 | + private boolean recurseTree(TreeNode currentNode, TreeNode p, TreeNode q) { |
| 27 | + |
| 28 | + // If reached the end of a branch, return false. |
| 29 | + if (currentNode == null) { |
| 30 | + return false; |
| 31 | + } |
| 32 | + |
| 33 | + // Left Recursion. If left recursion returns true, set left = 1 else 0 |
| 34 | + int left = this.recurseTree(currentNode.left, p, q) ? 1 : 0; |
| 35 | + |
| 36 | + // Right Recursion |
| 37 | + int right = this.recurseTree(currentNode.right, p, q) ? 1 : 0; |
| 38 | + |
| 39 | + // If the current node is one of p or q |
| 40 | + int mid = (currentNode == p || currentNode == q) ? 1 : 0; |
| 41 | + |
| 42 | + // If any two of the flags left, right or mid become True |
| 43 | + if (mid + left + right >= 2) { |
| 44 | + this.ans = currentNode; |
| 45 | + } |
| 46 | + |
| 47 | + // Return true if any one of the three bool values is True. |
| 48 | + return (mid + left + right > 0); |
| 49 | + } |
| 50 | + |
| 51 | + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { |
| 52 | + // Traverse the tree |
| 53 | + this.recurseTree(root, p, q); |
| 54 | + return this.ans; |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +// @lc code=end |
| 59 | + |
0 commit comments