|
| 1 | +package offer; |
| 2 | + |
| 3 | +/** |
| 4 | + * @author : CodeWater |
| 5 | + * @create :2022-07-12-1:04 |
| 6 | + * @Function Description :68.2 二叉树的最近公共祖先 |
| 7 | + */ |
| 8 | +public class _68_2TheRecentPublicAncestorOfTheBinaryTree { |
| 9 | + /** |
| 10 | + * Definition for a binary tree node. |
| 11 | + * public class TreeNode { |
| 12 | + * int val; |
| 13 | + * TreeNode left; |
| 14 | + * TreeNode right; |
| 15 | + * TreeNode(int x) { val = x; } |
| 16 | + * } |
| 17 | + */ |
| 18 | + class Solution { |
| 19 | + // 本题是一个普通的二叉树,不是二叉搜索树!!!!! |
| 20 | + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { |
| 21 | + /* |
| 22 | + 1. 当 left 和 right 同时为空 :说明 root 的左 / 右子树中都不包含p,q ,返回 null ; |
| 23 | +2.当 left 和 right 同时不为空 :说明 p,q 分列在 root 的 异侧 (分别在 左 / 右子树),因此 root为最近公共祖先,返回 rootroot ; |
| 24 | +3.当 left 为空 ,right 不为空 :p,q 都不在root 的左子树中,直接返回right 。具体可分为两种情况: |
| 25 | + 3.1p,q 其中一个在 root 的 右子树 中,此时 right 指向 pp(假设为 p ); |
| 26 | + 3.2p,q 两节点都在 root的 右子树 中,此时的 right 指向 最近公共祖先节点 ; |
| 27 | +4.当 left 不为空 , right 为空 :与情况 3. 同理; |
| 28 | +观察发现, 情况 1. 可合并至 3. 和 4. 内,详见文章末尾代码。 |
| 29 | +
|
| 30 | +
|
| 31 | + */ |
| 32 | + // 先序遍历 |
| 33 | + // 终止条件:当越过叶节点,则直接返回 null ;当 root 等于 p, qp,q ,则直接返回 root ; |
| 34 | + |
| 35 | + if( root == null || root == p || root == q ) return root; |
| 36 | + TreeNode left = lowestCommonAncestor( root.left , p , q ); |
| 37 | + TreeNode right = lowestCommonAncestor( root.right , p , q ); |
| 38 | + // 左树空,pq在右子树中 |
| 39 | + if( left == null ) return right ; |
| 40 | + // 右树空,pq在左子树中 |
| 41 | + if( right == null ) return left; |
| 42 | + return root; |
| 43 | + } |
| 44 | + |
| 45 | + } |
| 46 | +} |
0 commit comments