leetcode-235-Lowest Common Ancestor of a Binary Search Tree
2015-07-16 18:13
447 查看
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).”
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.
BST中,给出两个节点,求离它们最近的祖先。
因为是BST,root的左子树的值都小于root,root的右子树的值都大于root。
两个节点的公共路径的最后一个节点,即为最近的祖先。
递归
非递归
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.
BST中,给出两个节点,求离它们最近的祖先。
因为是BST,root的左子树的值都小于root,root的右子树的值都大于root。
两个节点的公共路径的最后一个节点,即为最近的祖先。
递归
/** * 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* solve(TreeNode* root,TreeNode* p,TreeNode* q){ if (p->val < root->val && q->val > root->val || p->val > root->val && q->val < root->val) return root; if (p->val == root->val || q->val == root->val) return root; if (p->val < root->val && q->val < root->val) return solve(root->left,p,q); if (p->val > root->val && q->val > root->val) return solve(root->right,p,q); } TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { return solve(root,p,q); } };
非递归
/** * 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) { 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; } } };
相关文章推荐
- mysql主从服务器配置
- 微端 代码project as air 分享
- FFmpeg源代码结构图 - 编码
- iOS开发系列--并行开发其实很容易--多线程
- C++——类继承
- eclipse使用技巧
- 通过NSX和AppVolumes部署基于角色的安全虚拟桌面
- ffmpeg 入门
- Java将时间加5分钟的方法
- 自己写一个线程池
- Kernel那些事儿之内存管理(8) --- Slab(中)
- 源码安装saltstack
- c++.primer.plus第五版第七章编程练习答案
- 基于Android的计步器(Pedometer)的讲解(一)——Fragment页面跳转
- SQL、LINQ、Lambda 三种用法互换
- Js 对象添加属性
- Java中静态代码块、非静态代码块、构造函数的执行顺序与作用
- PHP调用接口到阿里云OSS同步上传图片
- Oracle外部表介绍.
- java之redis篇(spring-data-redis整合)