leetcode之Lowest Common Ancestor of a Binary Search Tree
来源:互联网 发布:淘宝国际转运公司时效 编辑:程序博客网 时间:2024/04/29 18:03
题目:
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).”
解答:
根据BST的特性,进行路径查找,第一个路径分歧点就是LCA
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while(root)
{
if(p->val < root->val && q->val < root->val)
root = root->left;
else if(p->val > root->val && q->val > root->val)
root = root->right;
else
return root;
}
}
};
- LeetCode 之 Lowest Common Ancestor of a Binary Search Tree
- leetcode之Lowest Common Ancestor of a Binary Search Tree
- leetcode之Lowest Common Ancestor of a Binary Search Tree
- leetcode之Lowest Common Ancestor of a Binary Search Tree
- leetcode之Lowest Common Ancestor of a Binary Search Tree
- Leetcode 之 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: Lowest Common Ancestor of a Binary Search Tree
- [leetcode][dfs] 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] Lowest Common Ancestor of a Binary Search Tree
- LeetCode Lowest Common Ancestor of a Binary Search Tree
- leetCode(38):Lowest Common Ancestor of a Binary Search Tree
- leetcode-235-Lowest Common Ancestor of a Binary Search Tree
- 2014百度校园招聘面试题
- 求C++数组长度问题
- CodeForces 603A_Alternative Thinking (DP)
- 进一步理解C++构造与析构
- 11078Open Credit System
- leetcode之Lowest Common Ancestor of a Binary Search Tree
- android 源码剖析之------Window的内部实现机制(添加、删除、更新)
- 赋值不是初始化
- 获取和设置asp:RadioButtonList的值
- JQuery——级联下拉框
- 来到CSDN的第一天
- Servlet的使用
- 决策树 算法 理论
- UVa 11472 - Beautiful Numbers