|
| 1 | +/* |
| 2 | + * @lc app=leetcode.cn id=236 lang=java |
| 3 | + * |
| 4 | + * [236] 二叉树的最近公共祖先 |
| 5 | + * |
| 6 | + * https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/description/ |
| 7 | + * |
| 8 | + * algorithms |
| 9 | + * Medium (63.70%) |
| 10 | + * Likes: 591 |
| 11 | + * Dislikes: 0 |
| 12 | + * Total Accepted: 87.3K |
| 13 | + * Total Submissions: 136.7K |
| 14 | + * Testcase Example: '[3,5,1,6,2,0,8,null,null,7,4]\n5\n1' |
| 15 | + * |
| 16 | + * 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。 |
| 17 | + * |
| 18 | + * 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x |
| 19 | + * 的深度尽可能大(一个节点也可以是它自己的祖先)。” |
| 20 | + * |
| 21 | + * 例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4] |
| 22 | + * |
| 23 | + * |
| 24 | + * |
| 25 | + * |
| 26 | + * |
| 27 | + * 示例 1: |
| 28 | + * |
| 29 | + * 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 |
| 30 | + * 输出: 3 |
| 31 | + * 解释: 节点 5 和节点 1 的最近公共祖先是节点 3。 |
| 32 | + * |
| 33 | + * |
| 34 | + * 示例 2: |
| 35 | + * |
| 36 | + * 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 |
| 37 | + * 输出: 5 |
| 38 | + * 解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。 |
| 39 | + * |
| 40 | + * |
| 41 | + * |
| 42 | + * |
| 43 | + * 说明: |
| 44 | + * |
| 45 | + * |
| 46 | + * 所有节点的值都是唯一的。 |
| 47 | + * p、q 为不同节点且均存在于给定的二叉树中。 |
| 48 | + * |
| 49 | + * |
| 50 | + */ |
| 51 | + |
| 52 | +// @lc code=start |
| 53 | +/** |
| 54 | + * Definition for a binary tree node. |
| 55 | + * public class TreeNode { |
| 56 | + * int val; |
| 57 | + * TreeNode left; |
| 58 | + * TreeNode right; |
| 59 | + * TreeNode(int x) { val = x; } |
| 60 | + * } |
| 61 | + */ |
| 62 | +class Solution { |
| 63 | + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { |
| 64 | + if (root == null || p == root || q == root) { |
| 65 | + return root; |
| 66 | + } |
| 67 | + |
| 68 | + TreeNode left = lowestCommonAncestor(root.left, p, q); |
| 69 | + TreeNode right = lowestCommonAncestor(root.right, p, q); |
| 70 | + |
| 71 | + if (left == null) { |
| 72 | + return right; |
| 73 | + } |
| 74 | + if (right == null) { |
| 75 | + return left; |
| 76 | + } |
| 77 | + return root; |
| 78 | + } |
| 79 | +} |
| 80 | +// @lc code=end |
| 81 | + |
0 commit comments