2
到目前为止,我已经算出算法来添加到我的二叉搜索树中,但是我有点难以将它转换为代码。该算法如下:创建二叉搜索树
public void add(int v) {
Create a new node n to hold value v.
If tree is empty
Set root to n.
Else
Create temporary node reference m, initialized to root.
Loop looking for a gap (a null left or right pointer) that is on the
correct side of m for v
If v < m.value, look at the left pointer
If v >= m.value, look at the right pointer
If pointer on correct side is not null, set m to that child node and
continue looking
m = m.left or m = m.right
The search for insertion position stops when node m has a null pointer on
the correct side.
Insert the new node n at that position
m.left = n or m.right = n
}
到目前为止,我有:
public void add(int v) {
Node n = new Node(v);
if(root==null)
root = n;
else {
Node m = root;
while(...) {
if(...)
m = m.left;
else
m = m.right;
}
if(...)
m.left = m;
else
m.right = n;
}
}
我相信大多数的这是正确的,但我不知道需要做的地方标记为”什么。 ..“
我认为谷歌搜索会产生无数的这个问题的结果。 – Algorithmist
我确实有这个实现(它使用泛型):http://sdrv.ms/19qBooi(看看BinaryTree.java和TreeNode.java) – gparyani