[leetcode]: 235. Lowest Common Ancestor of a Binary Search Tree
来源:互联网 发布:2014新疆网络管制 编辑:程序博客网 时间:2024/05/21 09:50
1.题目
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).”
给一棵二叉搜索树,树上的两个节点v,w,求这两个节点的最低公共祖先
例如,节点2,8的最低公共祖先为6. 节点2,4的最低公共祖先为2.
2.分析
二叉搜索树BST满足,左节点的值<根节点的值<右节点的值。
所以从根节点开始往下搜索,如果:
当前节点值>两个节点的值,转到左子树
当前节点值<两个节点的值,转到右子树
介于两者直接,则找到了最低公共子节点。
题外话:如果不是BST,只是一棵普通的二叉树,那么这个问题就转换为求两个链表的第一个公共节点。分别求从根节点到指定节点的路径,然后找这两条路径的第一个汇合点。
3.代码
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { int maxv = p->val > q->val ? p->val : q->val; int minv = p->val + q->val - maxv; while (root) { if (root->val > maxv) root = root->left; else if (root->val < minv) 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
- 滑动菜单DrawerLayout
- 2.0后的Android studio的instant run为何物?
- 多态,向上(下转型),instanceof用法
- POJ 1520 Scramble Sort 笔记
- The Future of Real-Time SLAM and Deep Learning vs SLAM
- [leetcode]: 235. Lowest Common Ancestor of a Binary Search Tree
- JSP中四中属性的范围
- 略谈这几年的“筐技术”
- Cannot find installed version of python-django or python3-django
- HTML/CSS 学习笔记(三)
- 执行pip install 出现编码错误,UnicodeEncodeError:.....
- OC中的关键字: static extern const
- Html_Head部分及基本块级标签
- padding