Leetcode 235. Lowest Common Ancestor of a Binary Search Tree
2017-03-30 02:53
447 查看
// Recursive approach public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q); // both p and q are smaller than root, LCA must in the left child tree else if (root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q); // both p and q are larger than root, LCA must in the right child tree else return root; // root is in the middle of p and q, so root is the LCA } }
// iterative approach public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { while (true) { if (root.val > p.val && root.val > q.val) root = root.left; // search the left child tree else if (root.val < p.val && root.val < q.val) root = root.right; // search the right child tree else break; } return root; } }
相关文章推荐
- <LeetCode OJ> 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree LeetCode
- LeetCode *** 235. Lowest Common Ancestor of a Binary Search Tree
- [leetcode] 235.Lowest Common Ancestor of a Binary Search Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- [leetcode] 235. Lowest Common Ancestor of a Binary Search Tree 解题报告
- [leetcode] 235. Lowest Common Ancestor of a Binary Search Tree
- leetcode 每日一题 235. Lowest Common Ancestor of a Binary Search Tree
- leetcode:235. Lowest Common Ancestor of a Binary Search Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- (easy)LeetCode 235.Lowest Common Ancestor of a Binary Search Tree
- 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]235. Lowest Common Ancestor of a Binary Search Tree
- 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree(二叉搜索树的最低公共祖先)
- [LeetCode]235.Lowest Common Ancestor of a Binary Search Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- 【leetcode每日一题】235.Lowest Common Ancestor of a Binary Search Tree
- Leetcode:235. Lowest Common Ancestor of a Binary Search Tree(JAVA)