标签:
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.
思路:1.由于题目给出的条件是BST,即左节点小于等于根节点,右节点大于根节点。
2.如果题目所给出的两个子节点都在左子树那么它们都小于根节点,此时根节点往左子树方向移动,如果它们都在右子树那么它们都大于根节点,此时根节点往右子树方向移动。
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 //non-recursive version 11 public class Solution { 12 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 13 if (root == null || p == null || q == null) { 14 return null; 15 } 16 if (p == root || q == root) { 17 return root; 18 } 19 20 while (true) { 21 if (root.val > p.val && root.val > q.val) { 22 root = root.left; 23 } else if (root.val < p.val && root.val < q.val) { 24 root = root.right; 25 } else { 26 return root; 27 } 28 } 29 30 return null; 31 } 32 33 // recursive version 34 public class solution { 35 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 36 if (root == null || p == null || q == null) { 37 return null; 38 } 39 if (p == root || q == root) { 40 return root; 41 } 42 if (root.val > p.val && root.val > q.val) { 43 return lowestCommonAncestor(root.left, p, q); 44 } else if (root.val < p.val && root.val < q.val) { 45 return lowestCommonAncestor(root.right, p, q); 46 } else { 47 return root; 48 } 49 } 50 }
Lowest Common Ancestor of a Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/FLAGyuri/p/5271203.html