leetcode--Lowest Common Ancestor of a Binary Search Tree,addbinaryleetcode
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 allowa node to be a descendant of itself).”
_______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5
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樹,給出樹上的兩個節點,找出它們的最接近的共同祖先節點。
分類:二叉樹
解法1:由於題目給出的是BST樹,根據BST樹的性質,對於某個節點,其左子樹上的所有節點的值都比它小,右子樹上的所有節點的值都比它大。
對於根節點root而言,如果p,q兩個相比root,一大一小,說明root就是它們的LCA
如果都在比root小,說明它們的LCA在root的左子樹上。如果都比root大,說明它們的LCA在root的右子樹上。
如果它們有其中一個跟root相等,說明這個就是LCA
根據這個思路,我們很快寫出代碼:
/** * 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==null) return null; if(p.val<root.val&&root.val<q.val){//如果一左一右 return root; }else if(p.val>root.val&&root.val>q.val){//如果一左一右 return root; }else if(p.val<root.val&&root.val>q.val){//如果都在左邊,遞迴尋找左子樹 return lowestCommonAncestor(root.left,p,q); }else if(p.val>root.val&&q.val>root.val){//如果都在右邊,遞迴尋找右子樹 return lowestCommonAncestor(root.right,p,q); }else if(p.val==root.val){//如果和root相等 return p; }else if(q.val==root.val){//如果和root相等 return q; } return null; }}
解法2:解法2跟解法1的思路一樣,但是精簡了一下代碼,除了在左右子樹的情況,其餘情況我們都可以返回root
/** * 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==null) return null; if(p.val<root.val&&root.val>q.val){//如果都在左邊,遞迴尋找左子樹 return lowestCommonAncestor(root.left,p,q); }else if(p.val>root.val&&q.val>root.val){//如果都在右邊,遞迴尋找右子樹 return lowestCommonAncestor(root.right,p,q); }else{//其餘情況 return root; } }}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。