- 1143 Lowest Common Ancestor(30 分
- 236. Lowest Common Ancestor of a
- Leetcode-235题:Lowest Common Ance
- Leetcode-236题:Lowest Common Ance
- LeetCode Lowest Common Ancestor
- lintcode 88. Lowest Common Ances
- 235. Lowest Common Ancestor of a
- [PAT] c++ 1143. Lowest Common An
- 236. Lowest Common Ancestor of a
- 236 Lowest Common Ancestor of a
![](https://img.haomeiwen.com/i2985746/da0a2a4a8d9b4116.png)
解題思路 :
LCA 的第一題 沒有 parent pointer 所以回 true 的條件為
1.root = A or root = B
2.root 左邊跟 root 右邊都檢查出有 A 或著 B 存在 (即 A, B 在 root 兩邊)
C++ code :
<pre><code>
class Solution {
public:
/**
* @param root: The root of the binary search tree.
* @param A and B: two nodes in a Binary.
* @return: Return the least common ancestor(LCA) of the two nodes.
*/
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *A, TreeNode *B) {
// write your code here
if(!root || root == A || root == B) return root;
TreeNode *left = lowestCommonAncestor(root->left, A, B);
TreeNode *right = lowestCommonAncestor(root->right, A, B);
if(left && right) return root;
return left? left : right;
}
};
网友评论