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).”
_______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.
Subscribe to see which companies asked this question
p和q的LCA是恰好把p、q分叉的节点,也就是LCA的值介于p、q之间
从最高层的祖先root开始往下,
若不满足LCA条件,往p、q所在子树递归。
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 12 if((p.val - root.val)*(root.val - q.val) >= 0) return root; 13 return root.val > p.val ? lowestCommonAncestor(root.left,p,q) : lowestCommonAncestor(root.right,p,q); 14 } 15 }
解法二 非递归:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 12 while(root != null){ 13 if(root.val > p.val && root.val > q.val) root = root.left; 14 else if(root.val < p.val && root.val < q.val) root = root.right; 15 else return root; 16 } 17 return root; 18 } 19 }
时间: 2024-10-02 22:04:43