leetcode刷题,总结,记录,备忘235
2015-09-05 20:27
344 查看
leetcode235
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.
不算难的题目,之前像太复杂了,,,没绕过弯,看了别人的代码,突然就开朗了,之前自己还是有点蠢。根据根节点的值域和p,q两个节点的值域进行判断,如果都比根的节点值域小,就代表在左子树中,用根节点的左节点做递归,反之亦然。当2个节点的值域一个大于根节点的值域,一个小于的时候,代表找到,即返回。。。这么简单,我之前竟然蠢了好久,,,诶,,
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.
不算难的题目,之前像太复杂了,,,没绕过弯,看了别人的代码,突然就开朗了,之前自己还是有点蠢。根据根节点的值域和p,q两个节点的值域进行判断,如果都比根的节点值域小,就代表在左子树中,用根节点的左节点做递归,反之亦然。当2个节点的值域一个大于根节点的值域,一个小于的时候,代表找到,即返回。。。这么简单,我之前竟然蠢了好久,,,诶,,
/** * 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 (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; } } };
相关文章推荐
- JavaScript实现用户注册表单的简单检查
- 栈(stack)
- Spring常用注解
- python 字典 注意点
- C/C++笔试题目大全
- 排序算法之Java实现7——希尔排序算法
- Android Studio常见报错及处理办法
- 架构师速成-架构体系
- 阻止子View获取焦点方法
- 找一个字符串中重复的最长子序列
- 架构师速成-架构体系
- 排序算法之Java实现6——简单选择排序算法
- Linux 命令[0]:起航
- leetcode 217 Contains Duplicate(难易度:Easy)
- 排序算法之Java实现5——快速排序算法
- sql注入基础
- 编辑距离
- 排序之-----快速排序
- 排序算法之Java实现4——二路归并排序算法
- nginx索引目录配置