leetcode 235. Lowest Common Ancestor of a Binary Search Tree
- Lowest Common Ancestor of a Binary Search Tree:题目链接
递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null) { return null; } if (p.val < root.val && q.val < root.val) { return lowestCommonAncestor(root.left, p, q); } if (p.val > root.val && q.val > root.val) { return lowestCommonAncestor(root.right, p, q); } return root; } }
|
非递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null) { return null; } TreeNode curNode = root; while (curNode != null) { if (p.val < curNode.val && q.val < curNode.val) { curNode = curNode.left; }else if (p.val > curNode.val && q.val > curNode.val) { curNode = curNode.right; }else{ return curNode; } } return null; } }
|