[英]Adding and generating a binary search tree
我在弄清楚如何在二進制搜索樹中添加或插入節點時遇到麻煩。 目前,我有以下代碼:
public void add(int v) {
Node n = new Node(v);
if(root==null)
root = n;
else {
Node m = root;
while(...) { //not sure what to check
if(v < m.value)
m = m.left;
else
m = m.right;
}
if(...) //not sure what to check
m.left = n;
else
m.right = n;
}
}
然后我還想在一定范圍內生成n個節點。 我知道如何對數組執行此操作,但是我不確定如何對BST中的節點執行此操作。
public void generate(int n, int range) {
}
當您插入二叉樹時,您要走到找到沒有相應子節點的節點為止。 然后,將新節點插入該位置。
至於填充范圍內的數字,您可以使用與生成數組相同的方式生成它們,但是您可以add
方法,而不是將其插入數組。
使用當前方法,您將需要一個額外的變量來跟蹤父Node
public void add(int v) {
Node n = new Node(v);
if(root==null)
root = n;
else {
Node m = root,k;
while(m!=null) {
if(v < m.value){
k=m;
m = m.left;
}
else if(v > m.value){
k=m;
m = m.right;
}else{
return; //v already exists
}
}
if(v < k.value)
k.left=n;
else
k.right=n;
}
}
向BST添加值時,請橫穿樹,直到找到一個空白點,然后在該點插入新節點。
首先,我們從簡並的情況開始。 即,沒有節點,根為空/空。
偽代碼:
if root is null then
root = new node(value);
return;
end if
因此,我們在這里所做的只是構建樹的根節點。 它不包含葉節點。
現在所有后續插入都要求我們橫穿樹。
所以首先我們需要一個起點,它將是根節點。 然后,我們還需要知道是否已經到達一個空白點,可以在其中將新值插入樹中。 這需要跟蹤兩個變量。 一個用於保存我們正在檢查的當前節點,另一個用於保存該節點的父節點。
偽代碼:
# initialize tracking variables.
checkNode = root;
parentNode = checkNode;
while checkNode is null do
parent = checkNode; # want to save this for when we find a spot to store our new value
if valueOf(checkNode) equals value then return # the value is already stored
if value < valueOf(checkNode) then
# the new value is less than the value stored in this node so continue down the left branch
checkNode = checkNode.left
else
checkNode = checkNode.right # otherwise continue down the right branch
end while
# at this point checkNode will be null and parent will be set to a node that can store a new node with our value.
if value < valueOf(parent) then
parent.left = node(value) # store a new node in the left of the found parent node
else
parent.right = node(value)
我們正在做的是遍歷樹,將要添加的值與要檢查的節點的值進行比較。 我們還跟蹤正在檢查的節點的父節點,因為這是我們最終將要插入新節點的地方。 這是因為當checkNode為null時,我們結束了搜索。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.