Lowest Common Ancestor of a Binary Search Tree 寻找最低共同祖先
2015-12-02 09:53
429 查看
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).”
For example, the lowest common ancestor (LCA) of nodes
Another example is LCA of nodes
since a node can be a descendant of itself according to the LCA definition.
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 == NULL || p == NULL || q == NULL) return NULL; if(min(p->val,q->val) > root->val) return lowestCommonAncestor(root->right,p,q); else if(max(p->val,q->val) < root->val) return lowestCommonAncestor(root->left,p,q); else return root; } };
相关文章推荐
- 谈EXPORT_SYMBOL使用
- js之生命周期坑
- java.util.concurrent.CountDownLatch
- 實作解析:微信開發重點摘要 (5) - 獲取用戶訊息
- WebView 性能优化
- 问题:oracle 不等于;结果:Oracle中的不等于号
- Web前端慢加密
- LibSVM学习(三)——LibSVM使用规范
- ld: -pie can only be used when targeting iOS 4.2 or later
- 在webview中addJavascriptInterface,js调用java函数打包出现不响应,即使对混淆处理
- Android系统init.rc分析
- Git 远程仓库的管理和使用
- LeetCode 150 Evaluate Reverse Polish Notation
- plot函数用法(MATLAB)
- 日志报错Can't add self as subview
- Unicode编码完全探究(二)
- DOM对象和jQuery对象
- oracle的TEMP空间作用及涉及的操作
- 微信扫一扫打印照片的原理以及实现过程(持续更新中)
- Contiki简介