問題:
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
image.png
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
大意:
給出一個二叉查找樹(BST),在其中找到給出的兩個節點的最低的共同祖先(LCA)。
根據維基百科對LCA的定義:“最低共同祖先是指兩個節點v和w在T中有v和w作為后代節點的最低節點(我們允許節點是自己的祖先)。”
image.png
比如說,2和8的LCA是6。另一個例子,2和4的LCA是2,因為根據LCA的定義,一個節點可以是它自己的祖先。
思路:
這里要注意的地方是給出的二叉樹是一個二叉查找樹,所謂二叉查找樹是指:
- 若左子樹不空,則左子樹上所有結點的值均小于它的根結點的值;
- 若右子樹不空,則右子樹上所有結點的值均大于它的根結點的值;
- 左、右子樹也分別為二叉排序樹;
- 沒有鍵值相等的結點。
對于這個問題,如果是一個隨意的二叉樹要找LCA是比較麻煩的,要先找到目標節點的位置然后又反過來一層層找最低祖先。但是對于二叉查找樹就要簡單的多了,因為是排好序了的,可以簡單地找到位置。
我們根據目標節點的值和根節點的值來判斷目標節點在跟節點的左子樹上還是右子樹上,如果一個在左一個在右,就說明其LCA是根節點;如果都在左或者都在右,就對跟節點的左或者右子節點調用同樣的方法進行遞歸。
因為沒有鍵值相等的節點,所以判斷時不用考慮等于的情況,這道題中也不需要考慮節點為null的特殊情況,所以代碼很簡單。
代碼(Java):
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root.val - p.val > 0 && root.val - q.val > 0) return lowestCommonAncestor(root.left, p, q);
else if (root.val - p.val < 0 && root.val - q.val < 0) return lowestCommonAncestor(root.right, p, q);
else return root;
}
}
合集:https://github.com/Cloudox/LeetCode-Record