RA官宣主教練克里斯早已不在執教及BP!3月前已搬離基地!
阿新 • • 發佈:2022-04-03
題目連結:
劍指 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 = newHashMap<>(); 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 }