第19题 在二叉查找树中找到两个结点的最低公共祖先 Lowest Common Ancestor
来源:互联网 发布:聊城职业技术学院网络 编辑:程序博客网 时间:2024/05/17 04:50
本文来自《 programming interviews exposed》一书
题目:
Given the value of two nodes in a binary search tree, find the lowest common ancestor. You may assume that both values already exist in the tree.
The function prototype is as follows:
int findLowestCommonAncestor(node* root, int value 1, int value2);
20
/ \
8 22
/ \
4 12
/ \
10 14
比如在上面这个二叉搜索树中,要找4和14的lowest common ancestor, 就应该是8.
算法描述:
因为根节点是所有节点的祖先,又因为二叉树自身的性质,我们会得到,当两个目标节点都比当前节点小的时候,我们走左节点,当两个目标节点都比当前节点大的时候,我们走右节点。第一个碰到的节点的值在两个目标节点之间的节点就是 lowest common ancestor
int findLowestCommonAncestor(node* root, int value1, int value2) { node* curNode = root; while(1) { // go to the left child if(curNode->value>value1 && curNode->value>value2) curNode = curNode->left; // go to the right child else if (curNode->value < value1 && curNode->value < value2) curNode = curNode->right; else return curNode->value; }}
算法的时间复杂度是O(logn)
- 第19题 在二叉查找树中找到两个结点的最低公共祖先 Lowest Common Ancestor
- 面试题50 树中两个节点的最低公共祖先LCA(Lowest Common Ancestor )
- 二叉树中两个结点的最近公共祖先(Lowest Common Ancestor of a Binary Tree)
- 二叉树 之 lowest common ancestor 最低公共祖先
- 235. Lowest Common Ancestor of a Binary Search Tree | 二叉查找树两个节点的最低共同祖先
- LeetCode 236. Lowest Common Ancestor of a Binary Tree(二叉树的最低公共祖先)
- 二叉树中两个结点的最低公共祖先
- lowest common ancestor 最低公共祖先
- 最低公共祖先 lowest common ancestor
- 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(二叉搜索树的最低公共祖先)
- 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最低公共祖先(难)
- 树——在二叉树中找到两个节点的最低公共祖先LCA
- 题目:在二叉树中给出两个已知结点,求这两个结点的最低公共祖先
- 二叉树两个结点的最低公共祖先
- 二叉树两个结点的最低公共祖先
- 比赛题目 Give Me an E
- 集群与负载均衡
- 转置后的矩阵
- Collective Intelligence with Python 1
- 同一个网站空间,不同域名跳转到不同的路径
- 第19题 在二叉查找树中找到两个结点的最低公共祖先 Lowest Common Ancestor
- log4j 中 很搞笑的一段代码
- Mindmanager设置字体和默认字体
- Silverlight经典教程书籍汇总
- 几个Xaml开发Visual Studio 2010设置技巧
- 《一步一脚印 90后程序员》3
- 桃花庵歌
- http://acm.hdu.edu.cn/showproblem.php?pid=1248&&完全背包
- ASP.NET 显示当前文件所在路径