java 二叉搜索树寻找最小跟结点
来源:互联网 发布:debian官方软件源 编辑:程序博客网 时间:2024/06/11 07:15
题目:
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. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root==null||p==null||q==null){ return null; } if(Math.max(p.val,q.val)<root.val){ root = root.left; return lowestCommonAncestor(root,p,q); }else if(Math.min(p.val,q.val)>root.val){ root = root.right; return lowestCommonAncestor(root,p,q); } return root; }}
0 0
- java 二叉搜索树寻找最小跟结点
- 二叉树寻找父结点
- 二叉树8:寻找错误结点练习题
- 二叉树寻找给定结点p的下一个结点
- 数据结构与算法分析笔记与总结(java实现)--二叉树8:寻找错误结点练习题
- 二叉搜索树的下一个结点
- 二叉搜索树第k个结点
- LeetCode:寻找二叉树的最小深度
- 二叉搜索树两结点最低公共祖先结点
- 二叉树的创建,各种遍历,寻找结点,父结点,删除结点
- 寻找二叉树两个结点的最低共同父节点
- 二叉树 之 寻找某个结点所有的祖先
- 学习笔记41-寻找二叉树最近公共结点
- 二叉搜索树的第k个结点(二叉搜索树结点查找)
- 【二叉树】二叉搜索树的第k个结点
- Java 实现二叉搜索树的创建、查找、插入、删除结点
- 二叉搜索树的第k个结点(Java实现)
- 数据结构与算法分析笔记与总结(java实现)--二叉树21:二叉搜索树的第k个结点
- ubuntu下删除文件夹内所有的.svn文件
- 底部导航实现使子控件超出父控件的限制
- Java单元测试Junit(二)使用DBUnit扩展JUnit
- 【ExpandableListView】ExpandableListView互斥展开效果
- 标签
- java 二叉搜索树寻找最小跟结点
- 初始Android之Activity和Intent(二)
- Android数据存储之SharedPreference的commit()跟apply()的区别
- 32位整形数转化为IP地址
- Error running app: Instant Run requires 'Tools | Android | Enable ADB integration' to be enabled.
- Android自定义view 必须知道的 Android View绘制流程
- 数据报表JFreeChart的使用用例
- 安卓基础:BaseAdapter的使用与优化
- 线程间通信