Mock.js模擬介面資料
https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/
給定一個二叉樹, 找到該樹中兩個指定節點的最近公共祖先。
百度百科中最近公共祖先的定義為:“對於有根樹 T 的兩個結點 p、q,最近公共祖先表示為一個結點 x,滿足 x 是 p、q 的祖先且 x 的深度儘可能大(一個節點也可以是它自己的祖先)。”
例如,給定如下二叉樹: root = [3,5,1,6,2,0,8,null,null,7,4]
示例 1:
輸入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
解釋: 節點 5 和節點 1 的最近公共祖先是節點 3。
示例 2:
輸入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
輸出: 5
解釋: 節點 5 和節點 4 的最近公共祖先是節點 5。因為根據定義最近公共祖先節點可以為節點本身。
說明:
- 所有節點的值都是唯一的。
- p、q 為不同節點且均存在於給定的二叉樹中。
思路:
沒有特別好的思路,唯一想到通過dfs找到對應的節點,找到後,把值放入一個棧中,再跳出遞迴把上一層的值一個個放入棧中。
最後得到兩個棧,棧中分別是兩個節點的父節點(和自身),然後利用棧先進後出的特點,一個個往外拿,最先拿出的是root節點,最後一個相同的節點則是最近公共祖先,
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { Stack<TreeNode> stackp = new Stack<>(); Stack<TreeNode> stackq = new Stack<>(); public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { check(root,p,stackp); check(root,q,stackq); TreeNode result = null; while(stackp.size() != 0 && stackq.size() != 0 ){ if(stackp.peek() == stackq.peek()){ result = stackp.pop(); stackq.pop(); } else{ break; } } return result; } private boolean check(TreeNode now, TreeNode target, Stack<TreeNode> stack){ if(null == now){ return false; } if(now.val==target.val){ stack.push(now); return true; } boolean find; find = check(now.left, target, stack) || check(now.right, target, stack); if(find == true){ stack.push(now); } return find; } }
他人題解
https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/solution/mian-shi-ti-68-ii-er-cha-shu-de-zui-jin-gong-gon-7/
題解的主要思路是將幾種情況都分析了下,分為四種情況。 一種是p和q在root的左右子樹中,這樣p,q的公共節點為root。 一種是p,q在root的同一側,那最近的公共節點為p或q
程式碼如下:
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || root == p || root == q) return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if(left == null && right == null) return null; // 1.
if(left == null) return right; // 3.
if(right == null) return left; // 4.
return root; // 2. if(left != null and right != null)
}
}
作者:jyd
連結:https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/solution/mian-shi-ti-68-ii-er-cha-shu-de-zui-jin-gong-gon-7/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。```