235. Lowest Common Ancestor of a Binary Search Tree LeetCode
2016-02-10 12:55
323 查看
题意:求一棵二叉搜索树的两个节点的最近公共祖先。
题解:利用二叉搜索树的性质,可以很方便的求解。递归的去求两个节点的最近公共祖先,首先看两个节点的值与当前节点的大小关系,如果两个节点的值一个小于等于当前节点值,另一个大于等于当前节点的值,那么这个当前节点一定是他们的最近公共祖先。如果两个节点值都要比当前节点值小,那么最近公共祖先应该在左子树里面,递归求解。类似的,如果都大与当前节点的值,那么最近公共祖先应该在右子树里面,递归求解。
题解:利用二叉搜索树的性质,可以很方便的求解。递归的去求两个节点的最近公共祖先,首先看两个节点的值与当前节点的大小关系,如果两个节点的值一个小于等于当前节点值,另一个大于等于当前节点的值,那么这个当前节点一定是他们的最近公共祖先。如果两个节点值都要比当前节点值小,那么最近公共祖先应该在左子树里面,递归求解。类似的,如果都大与当前节点的值,那么最近公共祖先应该在右子树里面,递归求解。
class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(root->val == p->val || root->val == q->val) return root; if(root->val < p->val && root->val < q->val) return lowestCommonAncestor(root->right,p,q); else if(root->val > p->val && root->val > q->val) return lowestCommonAncestor(root->left,p,q); else return root; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解