LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
来源:互联网 发布:中小学教师网络培训 编辑:程序博客网 时间:2024/05/16 15:46
题意:求一颗二叉搜索树的上两个节点的最小公共子序列
思路:我们根据BST的性质可知,对于一个节点p,如果存在左子树,那么它左子树上的点全都小于p,如果存在右子树,那么它右子树上的点都大于p。
因此根据这个性质,我们可以知道如果这两个节点的值都小于p,则他两个一定在p的左子树上,如果都大于p,则一定在其右子树上。
递归:
class Solution{public: TreeNode* lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q){ if(max(p->val, q->val) < root->val){ return lowestCommonAncestor(root->left, p, q); } else if(min(p->val, q->val) > root->val){ return lowestCommonAncestor(root->right, p, q); } else{ return root; } }};
非递归:
class Solution{public: TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q){ while(1){ if(max(p->val, q->val) < root->val){ root = root->left; } else if(min(p->val, q->val) > root->val){ root = root->right; } else{ return root; } } }};
0 0
- 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
- 235. Lowest Common Ancestor of a Binary Search Tree LeetCode
- 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] 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-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.[Leetcode]Lowest Common Ancestor of a Binary Search Tree
- 【leetcode】235. Lowest Common Ancestor of a Binary Search Tree
- swift gcd 延时调用封装
- key_len计算规则
- iOS开发中控制屏幕旋转,个别界面强制横屏
- 手把手教你做爬虫---基于NodeJs
- Hibernate三种检索策略的优缺点对比
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- API接口设计 - 身份认证篇
- 集合竞价 CCF java实现 (大部分代码是借鉴的别人的,)
- java 反射机制详解
- 常用服务的端口
- JAVA操作mongoDB
- Hadoop namenode 不能启动解决方案
- python 爬虫好文 urllib cookie beautifulsoap
- IO流笔记第五发缓冲流读写及简单file类操作