leetcode刷题,总结,记录,备忘235
来源:互联网 发布:vscode web插件 编辑:程序博客网 时间:2024/05/29 17:39
leetcode235
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 2
and 8
is 6
. Another example is LCA of nodes 2
and 4
is 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 (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; } }};
0 0
- leetcode刷题,总结,记录,备忘235
- leetcode刷题。总结,记录,备忘 104
- leetcode刷题。总结,记录,备忘 100
- leetcode刷题。总结,记录,备忘 191
- leetcode刷题。总结,记录,备忘。168
- leetcode刷题, 总结,记录,备忘 171
- leetcode刷题 ,总结,记录,备忘。144
- leetcode刷题,总结,记录, 备忘 141
- leetcode刷题,总结,记录,备忘。116
- leetcode刷题,总结,记录,备忘。96
- leetcode刷题。记录,总结,备忘。217
- leetcode 刷题, 总结,记录,备忘 35
- leetcode刷题,总结,记录,备忘 226
- leetcode刷题,总结,记录,备忘 169
- leetcode刷题,总结,记录,备忘137
- leetcode刷题,总结,记录,备忘83
- leetcode刷题,总结,记录,备忘70
- leetcode刷题,总结,记录,备忘 108
- 排序算法之Java实现5——快速排序算法
- leetcode 217 Contains Duplicate(难易度:Easy)
- POJ 2282 The Counting Problem (数位dp)
- 架构师速成-架构体系
- 排序算法之Java实现6——简单选择排序算法
- leetcode刷题,总结,记录,备忘235
- 机房收费系统 之 组合查询
- 排序算法之Java实现7——希尔排序算法
- C/C++笔试题目大全
- JavaScript实现用户注册表单的简单检查
- Memcached之——与Spring集成(单服务器)
- Eclipse添加Android项目工程后res文件夹下layout/values/drawable文件不可见
- 1004. 成绩排名 (20)
- 腾讯2013研发笔试题目