剑指 Offer 68 - II. 二叉树的最近公共祖先

题目链接:
剑指 Offer 68 - II. 二叉树的最近公共祖先 - 力扣(LeetCode) (leetcode-cn.com)

方法1(易理解,代码量大):

 1 //方法1:用一个HashMap存入所有节点对应的父节点(建立映射关系),然后去遍历其中一个节点的所有父节点即
 2     //(包括父节点的父节点等)
 3     
 4     public static TreeNode lowestCommonAncestor1(TreeNode root,TreeNode p,TreeNode q) {
 5         HashMap<TreeNode,TreeNode> fatherMap = new HashMap<>();
 6         fatherMap.put(root, root);
 7         process1(root,fatherMap);
 8         HashSet<TreeNode> set = new HashSet<>();
 9         set.add(root);
10         TreeNode cur = p;
11         while (cur != fatherMap.get(cur)) {
12             set.add(cur);
13             cur = fatherMap.get(cur);
14         }
15         cur = q;
16         while (cur != fatherMap.get(cur)) {
17             if (set.contains(cur) == true) {
18                 return cur;
19             }
20             cur = fatherMap.get(cur);
21         }
22         return cur;
23     }
24     
25     public static void process1(TreeNode root,HashMap<TreeNode,TreeNode> fatherMap) {
26         if (root == null) {
27             return;
28         }
29         fatherMap.put(root.left, root);
30         fatherMap.put(root.right, root);
31         process1(root.left,fatherMap);
32         process1(root.right,fatherMap);
33     }

 

方法2(难理解,代码简洁):

 1 //方法2:
 2     public static TreeNode lowestCommonAncestor(TreeNode root,TreeNode p,TreeNode q) {
 3         if (root == null || root == p || root == q) {//保证返回值只要null,p,q三者
 4             return root;
 5         }
 6         TreeNode left = lowestCommonAncestor(root.left,p,q);//找其左子树是否含有p或q
 7         TreeNode right = lowestCommonAncestor(root.right,p,q);//找其右子树是否含有p或q
 8         if (left != null && right != null) {//如果从root节点的左右子树都含有p,q,则第一次出现这种情况的节点
 9                                             //就是所要的节点,直接return root;得到结果
10             return root;
11         }
12         return left != null ? left : right;//有p,q优先return p,q;如果都没有就return null
13     }

 

posted @ 2022-04-14 22:56  jue1e0  阅读(20)  评论(0)    收藏  举报