一,問題描述
請構造一棵二叉查找樹,並給定兩個結點,請找出這兩個結點的最低公共祖先結點。
這里假設二叉查找樹中的結點的權值存儲是整型數字(見代碼中的BinaryNode內部類),最低公共祖先結點如下:結點5 和 結點12 的最低公共祖先結點是結點10
二,實現思路
假設給定的兩個結點的權值分別為 node1 和 node2
如果根的權值處於 node1 和 node2 之間,則根就是它們的最低公共祖先結點
如果根的權值比 node1 和 node2 都大,則它們的最低公共祖先結點在根的左子樹中
如果根的權值比 node1 和 node2 都小,則它們的最低公共祖先結點在根的右子樹中
因此,這可以用遞歸來實現。
三,代碼實現
首先得構造一棵二叉查找樹。具體構造可參考:二叉樹的構造
構造好之后,調用lowestCommonParentNode方法即可找出最低公共祖先結點的權值。
public class LowCommonNode { private class BinaryNode{ BinaryNode left; BinaryNode right; int ele; public BinaryNode(int ele) { this.ele = ele; left = right = null; } } private BinaryNode root; private void buildTree(int[] arr){ for (int i : arr) { insert(i); } } private void insert(int ele){ root = insert(root, ele); } private BinaryNode insert(BinaryNode root, int ele){ if(root == null) return new BinaryNode(ele); if(root.ele > ele)//insert left root.left = insert(root.left, ele); else if(root.ele < ele) root.right = insert(root.right, ele); else root.left = insert(root.left, ele);//相等時,放在左邊 return root; } /** * 求解二叉查找樹中 node1 和 node2 代表的節點的 最低公共祖先結點 * 首先讓node1總是代表權值較小的那個結點. * 對於二叉查找樹而言: * 如果根的權值處於 node1 和 node2 之間,則根就是它們的最低公共祖先結點 * 如果根的權值比 node1 和 node2 都大,則它們的最低公共祖先結點在根的左子樹中 * 如果根的權值比 node1 和 node2 都小,則它們的最低公共祖先結點在根的右子樹中 */ public int lowestCommonParentNode(BinaryNode root, int node1, int node2) { if(node1 > node2) { int tmp = node1; node1 = node2; node2 = tmp; } assert node1 < node2; if(root == null) throw new IllegalArgumentException(" neither node1 nor node2 contains in binary search tree "); if(root.ele > node1 && root.ele < node2) return root.ele; if(root.ele > node1 && root.ele > node2)//if(root.ele > node2) //在左子樹中查找最低公共祖先結點 return lowestCommonParentNode(root.left, node1, node2); else//root.ele < node1 //在右子樹中查找最低公共祖先結點 return lowestCommonParentNode(root.right, node1, node2); } //hapjin test public static void main(String[] args) { LowCommonNode lcn = new LowCommonNode(); int[] arr = {20,10,30,5,15,25,40,12,18}; lcn.buildTree(arr);//build a binary search tree // node1 and node2 should exist in arr,or will throw IllegalArgumentException int node1 = 5; int node2 = 12; //should build Tree before invoke lowestCommonParentNode System.out.println(lcn.lowestCommonParentNode(lcn.root, node1, node2)); } }
四,參考資料