有人能举例说明二叉树和二叉搜索树的区别吗?
当前回答
正如上面每个人都解释了二叉树和二叉搜索树的区别,我只是补充如何测试给定的二叉树是否是二叉搜索树。
boolean b = new Sample().isBinarySearchTree(n1, Integer.MIN_VALUE, Integer.MAX_VALUE);
.......
.......
.......
public boolean isBinarySearchTree(TreeNode node, int min, int max)
{
if(node == null)
{
return true;
}
boolean left = isBinarySearchTree(node.getLeft(), min, node.getValue());
boolean right = isBinarySearchTree(node.getRight(), node.getValue(), max);
return left && right && (node.getValue()<max) && (node.getValue()>=min);
}
希望对你有所帮助。抱歉,如果我转移了话题,因为我觉得这里值得一提。
其他回答
A binary tree is made of nodes, where each node contains a "left" pointer, a "right" pointer, and a data element. The "root" pointer points to the topmost node in the tree. The left and right pointers recursively point to smaller "subtrees" on either side. A null pointer represents a binary tree with no elements -- the empty tree. The formal recursive definition is: a binary tree is either empty (represented by a null pointer), or is made of a single node, where the left and right pointers (recursive definition ahead) each point to a binary tree.
二叉搜索树(BST)或“有序二叉树”是一种二叉树,其中节点是按顺序排列的:对于每个节点,其左子树中的所有元素都小于该节点(<),而其右子树中的所有元素都大于该节点(>)。
5
/ \
3 6
/ \ \
1 4 9
上面所示的树是一棵二叉搜索树——“根”节点为5,其左子树节点(1,3,4)< 5,右子树节点(6,9)为> 5。递归地,每个子树也必须服从二叉搜索树约束:在(1,3,4)子树中,3是根,1 < 3和4 > 3。
注意问题中的确切措辞——“二叉搜索树”不同于“二叉树”。
正如上面每个人都解释了二叉树和二叉搜索树的区别,我只是补充如何测试给定的二叉树是否是二叉搜索树。
boolean b = new Sample().isBinarySearchTree(n1, Integer.MIN_VALUE, Integer.MAX_VALUE);
.......
.......
.......
public boolean isBinarySearchTree(TreeNode node, int min, int max)
{
if(node == null)
{
return true;
}
boolean left = isBinarySearchTree(node.getLeft(), min, node.getValue());
boolean right = isBinarySearchTree(node.getRight(), node.getValue(), max);
return left && right && (node.getValue()<max) && (node.getValue()>=min);
}
希望对你有所帮助。抱歉,如果我转移了话题,因为我觉得这里值得一提。
在二叉树中,每个节点有两个子节点:左节点和右节点。 二叉搜索树是一种特殊的树,其中节点被排序,左节点比父节点小,左节点比父节点大。 二叉树允许重复值,二叉搜索树不允许重复值,而且在二叉搜索树中执行任何类型的操作都比在二叉树中更快,因为BST是排序的
二叉树:每个节点最多有两个叶的树
1
/ \
2 3
二叉搜索树:用于搜索。二叉树,其中左子节点只包含值小于父节点的节点,而右子节点只包含值大于或等于父节点的节点。
2
/ \
1 3
二叉搜索树是一种特殊的二叉树,它表现出如下性质:对于任意节点n, n的左子树中每个后代节点的值都小于n,而右子树中每个后代节点的值都大于n。
推荐文章
- set()是如何实现的?
- .Net数据结构:ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary—速度,内存,以及何时使用每个?
- 为什么std::map被实现为红黑树?
- 实现嵌套字典的最佳方法是什么?
- 段树、区间树、二叉索引树和范围树之间有什么区别?
- 为什么我应该使用Deque而不是Stack?
- .Net中的优先级队列
- 为什么java.util.Set没有get(int index)?
- Python集vs列表
- 地图和字典的区别是什么?
- 跳跃表vs.二叉搜索树
- 谷歌Chrome显示JSON AJAX响应树,而不是纯文本
- 如何将列表转换为地图?
- 为什么我们没有一个数据结构
- 树数据结构