目錄
- 1. 題目
- 2. 解題思路
- 3. 資料型別功能函式總結
- 4. java代碼
1. 題目
定一個二叉搜索樹, 找到該樹中兩個指定節點的最近公共祖先,
百度百科中最近公共祖先的定義為:“對于有根樹 T 的兩個結點 p、q,最近公共祖先表示為一個結點 x,滿足 x 是 p、q 的祖先且 x 的深度盡可能大(一個節點也可以是它自己的祖先),”
例如,給定如下二叉搜索樹: root = [6,2,8,0,4,7,9,null,null,3,5]
示例 1:
輸入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
輸出: 6
解釋: 節點 2 和節點 8 的最近公共祖先是 6,
示例 2:
輸入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
輸出: 2
解釋: 節點 2 和節點 4 的最近公共祖先是 2, 因為根據定義最近公共祖先節點可以為節點本身,
說明:
所有節點的值都是唯一的,
p、q 為不同節點且均存在于給定的二叉搜索樹中,
作者:Krahets
鏈接:https://leetcode.cn/leetbook/read/illustration-of-algorithm/575kd2/
來源:力扣(LeetCode)
著作權歸作者所有,商業轉載請聯系作者獲得授權,非商業轉載請注明出處,
2. 解題思路
利用二叉搜索樹的大小順序判斷待搜索的節點在root節點的左右:
- 如果待搜索的節點在
root節點的兩邊,則root是公共祖先節點; - 如果待搜索的節點在
root節點的左邊,則公共祖先節點在root左子樹; - 如果待搜索的節點在
root節點的右邊,則公共祖先節點在root右子樹;
如果公共祖先節點在左右子樹中,可以使用遞回來查找,
3. 資料型別功能函式總結
//無
4. java代碼
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null){
return null;
}
else{
if(root.val>p.val && root.val>q.val){
return lowestCommonAncestor(root.left, p, q);
}
else if(root.val<p.val && root.val <q.val){
return lowestCommonAncestor(root.right, p, q);
}
else{
return root;
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/546289.html
標籤:Java
