Lowest Common Ancestor of a Binary Search Tree 递归寻找二叉查找树公共祖先
2015-08-29 13:03
609 查看
Lowest Common Ancestor of a Binary Search Tree
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).”
_______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5
For example, the lowest common ancestor (LCA) of nodes
2and
8is
6.
Another example is LCA of nodes
2and
4is
2,
since a node can be a descendant of itself according to the LCA definition.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(root->val==p->val) return p; else if(root->val==q->val) return q; else if(root->val > p->val && root->val > q->val) return lowestCommonAncestor(root->left,p,q); else if(root->val < p->val && root->val < q->val) return lowestCommonAncestor(root->right,p,q); else return root; } };
相关文章推荐
- 剑指Offer面试题:13.调整数组顺序使奇数位于偶数前面
- RecyclerView实现瀑布流效果(图文详解+源码奉送)
- RecyclerView实现瀑布流效果(图文详解+源码奉送)
- RecyclerView实现瀑布流效果(图文详解+源码奉送)
- jquery input change事件
- RecyclerView实现瀑布流效果(图文详解+源码奉送)
- Opencv实现画笔的功能
- TCP.Receiver C# 版本TCP协议接收器 V1.0.03
- 大龄屌丝自学笔记--Java零基础到菜鸟--013
- iOS的socket开发基础
- Oracle(三)--> 其他数据库对象(简单扼要论序列)
- jquery一个控件绑定多个事件
- 将图片生成pkl格式的文件(多层循环)
- Web前端开发规范文档
- 接上次OC中特有的语法
- 共轭梯度法,最速下降法和牛顿法
- Leetcode: Word Break
- div块级元素内文字换行word-wrap, word-break,white-space。
- HTTP协议
- BZOJ1189: [HNOI2007]紧急疏散evacuate 二分+最大流