我的方法是假設從BST返回一個隨機節點,但它不能正常工作,我不確定原因。該方法假設在遞增計數器的同時使用前序遍歷來遍歷樹。一旦計數器等於隨機生成的數字,則假定返回該節點。從樹中獲取隨機節點
// get random node
public Node getRandomNode(Node root) {
// get random value between 0 to size of BST
Random ran = new Random();
int ranNum = ran.nextInt(size + 1);
Node temp = root;
System.out.println("random number is: " + ranNum);
root = getRandomNode(ranNum, temp);
return root;
}
int count = 0;
public Node getRandomNode(int ranNum, Node temp) {
// traverse through the tree and increment count until count is the
// random number,
// in which case return the node it is on
if (temp != null && count != ranNum) {
count++;
temp = getRandomNode(ranNum, temp.left);
System.out.println(temp.data);
temp = getRandomNode(ranNum, temp.right);
}
// if count is equal to the randomly generated number
return temp;
}
編輯: 使用BFS
public Node getRandomNode(int ranNum, int count, Node temp) {
if(temp == null)
return null;
Queue<Node> q = new LinkedList<Node>();
q.add(temp);
count++;
while(!q.isEmpty() && count != ranNum) {
Node n = q.remove();
System.out.println(" " + n.data);
if(count == ranNum) {
System.out.println("final node: " + n.data);
return n;
}
if(n.left != null) {
q.add(n.left);
count++;
}
if(n.right != null) {
q.add(n.right);
count++;
}
}
return temp;
}
你會如何建議我遍歷左,右鍵的節點?我正在考慮使用'getRandomNode(ranNum,temp.left);「而不是'temp = getRandomNode(ranNum,temp.left);' (與右邊相同的東西)遍歷樹,但後來我不知道如何保存返回指針所在的位置 –
問題是,假設你必須使用預置遍歷,你需要一些東西從你的返回值告訴你你已經完成了,可能的修正是使用節點的包裝器或者修改節點類(過度使用),在調用之間檢查你的全局計數變量(可行,但我不喜歡全局變量),或者在沒有達到count變量的情況下返回null(有些人不喜歡返回null來表示事物)我假設這是一個任務,所以我試圖不給你一個答案 – billie
好的我會嘗試你的建議,並在稍後給你一個更新。而且我不知道自從夏天開始,我只是在開發編碼採訪中遇到問題,我有時間!這本書有不同的解決方案,但這是我想到的第一個解決方案,所以我想繼續。 –