【发布时间】:2014-07-09 15:02:17
【问题描述】:
当我创建 BST 时,在插入节点期间,我检查新节点的值是小于左孩子还是大于右孩子。然后我向下遍历,直到找到插入节点的正确位置。现在假设我有一棵二叉树,我想创建一棵树,我该怎么做?我需要使用 BFS 算法吗?
谢谢
【问题讨论】:
标签: algorithm data-structures tree binary-tree
当我创建 BST 时,在插入节点期间,我检查新节点的值是小于左孩子还是大于右孩子。然后我向下遍历,直到找到插入节点的正确位置。现在假设我有一棵二叉树,我想创建一棵树,我该怎么做?我需要使用 BFS 算法吗?
谢谢
【问题讨论】:
标签: algorithm data-structures tree binary-tree
这不是插入在 BST 中的工作方式, 新值应该与当前节点而不是其子节点进行比较,如果它小于当前节点的值,如果有左节点,则向左遍历,如果不存在左节点,则在此处插入值.右侧也是如此,但如果比较结果大于当前节点(BST中没有重复值)。
您的问题是关于如何创建二叉树而不是 BST, 如果你想要一个简单的二叉树来构造一棵完整的二叉树,那么只需从左到右逐层插入节点。当然 BFS 是逐层工作的,但它是一种搜索算法,你不需要搜索树,因为你是从头开始构建的。
编辑: 如果您想要一个更简单的二叉树构造版本,只需在一个分支中一直向下插入 2 个节点,无需回溯,即使您也插入 1 个节点,仍然是二叉树。
另一个编辑: 每一个BST都是一棵二叉树,每一个二叉树都是一棵树 并且这个论点不能倒置(例如,并非每个 BT 都是 BST ...等)。所以如果你有一个 BT,它已经是一棵树了。
问候,
【讨论】:
在这里,我正在制作一个基于权重的二叉树,这对 BFS 很有用,因为它可以保持树的平衡..
我会在Java 中这样实现它:
class BT_Node
{
public int value;
public int depth;
public long weight;
public BT_Node left, right;
public BT_Node (int value, int depth)
{
this.depth = depth;
this.value = value;
this.weight = 0;
this.left = this.right = null;
}
}
class BT
{
private BT_Node root;
public long size ()
{
return (root!=null ? root.weight : 0);
}
public long size (BT_Node node)
{
return (node!=null ? node.weight : 0);
}
public void insert (int value)
{
int depth = 0;
BT_Node parent = root;
if (root == null)
{
root = new BT_Node (value, 0);
}
else
{
root.weight++;
while (parent.left!=null && parent.right!=null)
{
if (parent.left.weight <= parent.right.weight)
parent=parent.left;
else
parent=parent.right;
parent.weight++;
}
if (parent.left == null)
parent.left = new BT_Node (value, parent.depth+1);
else
parent.right = new BT_Node (value, parent.depth+1);
}
}
}
【讨论】: