leetcode 235 Lowest Common Ancestor of a Binary Search Tree(难易度:Easy)
来源:互联网 发布:mysql cast 编辑:程序博客网 时间:2024/06/06 01:47
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 allowa 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; * struct TreeNode *left; * struct TreeNode *right; * }; */struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) { struct TreeNode *cur = root; while(true) { if(cur->val > p->val && cur->val > q->val) cur = cur->left; else if(cur->val < p->val && cur->val < q->val) cur = cur->right; else return cur; }}原题地址:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
0 0
- leetcode 235 Lowest Common Ancestor of a Binary Search Tree(难易度:Easy)
- [Leetcode 235, Easy] Lowest Common Ancestor of a Binary Search Tree
- LeetCode #235 - Lowest Common Ancestor of a Binary Search Tree Easy
- 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
- 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
- NSIS DerectUI 皮肤插件 免费使用!!支持异性,动画!!
- Android Fragment——管理Fragment
- Rabbitmq学习整理1
- chrome使用技巧
- CentOS下使用VIM打造C/C++开发环境
- leetcode 235 Lowest Common Ancestor of a Binary Search Tree(难易度:Easy)
- iPad开发第一天
- 多线程编程1-NSThread
- 【Material Design视觉设计语言】UI组件设计(七):网格
- 题目:编写一个程序,创建一个单链表,需要完成以下要求 1. 用户输入一组整数,以0作为结束标志,将这一组整数存放在链表中(0不存放),并打印该链表中的值。 2. 删除第5个元素,并打印删除后的结
- iOS 大型项目开发漫谈
- Spring MVC详解(四) Controller接口控制器详解(1)
- 整理网上资料---C标准库值篇二 :标准库源码下载地址、标准库手册下载地址
- ios禁用多按钮同时点下的效果