[英]Binary Tree Sorrt Java Recursive
我在Java中使用Binary Tree Sort遇到了一些麻煩。 我需要創建以下方法,但我不知道如何正確實現位置(pos)。 練習是用給定的簽名實現二叉樹排序。 然后,我們應該初始化一個int [],其大小必須至少是樹中Node的大小。 方法
int binSort(節點node,int [] a,int pos){...}
應該將每個節點/葉子的值放在位置pos的數組a中。 我不允許使用全局變量! 如您所見,我們需要實現inOrder遍歷
public class BinaryTree {
Node root;
int elements;
public BinaryTree() {
this.elements = 0;
}
public void addNode(int key, String name) {
Node newNode = new Node(key, name);
if (root == null) {
root = newNode;
} else {
Node focusNode = root;
Node parent;
while (true) {
parent = focusNode;
if (key < focusNode.getPriority()) {
focusNode = focusNode.getLeftChild();
if (focusNode == null) {
parent.setLeftChild(newNode);
return;
}
} else {
focusNode = focusNode.getRightChild();
if (focusNode == null) {
parent.setRightChild(newNode);
return;
}
}
}
}
}
public int binSort(Node focusNode, int[] a, int pos) {
int tmp = pos++;
if (focusNode != null) {
if (focusNode.getLeftChild() != null) {
binSort(focusNode.getLeftChild(), a, tmp);
}
System.out.println(focusNode.toString() + " - " + tmp++);
if (focusNode.getRightChild() != null) {
binSort(focusNode.getRightChild(), a, tmp);
}
return focusNode.getPriority();
}
return -1;
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.addNode(50, "Boss");
tree.addNode(30, "Boss");
tree.addNode(10, "Boss");
tree.addNode(70, "Boss");
tree.addNode(9, "Boss");
tree.addNode(15, "Boss");
tree.addNode(78, "Boss");
tree.addNode(36, "Boss");
int[] a = new int[8];
tree.binSort(tree.root, a, 0);
System.out.println(tree.root.getPriority());
System.out.println("");
System.out.println(Arrays.toString(a));
}
}
我的輸出:老板有一把鑰匙9-0
老板有一把鑰匙10-0
老板有一把鑰匙15-1
老板有一把鑰匙30-0
老板有一把鑰匙36-1
老板有一把鑰匙50-0
老板有一把鑰匙70-1
老板有一把鑰匙78-2
只需忽略“ Boss”(此刻這只是一個無用的值!),重要的部分是應放入數組中的特定值是有序排列的(9,10,15,30,..,78),但是職位不是! (0,0,1,0,1,0,1,2)我不知道該如何解決。
順便說一句。 類“節點”:
String val;
int priority;
Node leftChild;
Node rightChild;
public Node(int priority, String val) {
this.priority = priority;
this.val = val;
}
public int getPriority() {
return this.priority;
}
public String getVal() {
return this.val;
}
public Node getLeftChild() {
return leftChild;
}
public Node getRightChild() {
return rightChild;
}
public void setLeftChild(Node child) {
this.leftChild = child;
}
public void setRightChild(Node child) {
this.rightChild = child;
}
public String toString() {
return val + " has a key " + priority;
}
希望您能幫助我解決這個問題。
好的,我自己找到了解決方案:)
public int binSort(BinTreeNode nnode, int[] a, int pos) {
if (nnode != null) {
if (nnode.getLeftChild() != null) {
pos = binSort(nnode.getLeftChild(), a, pos);
}
a[pos] = nnode.getValue();
pos++;
if (nnode.getRightChild() != null) {
pos = binSort(nnode.getRightChild(), a, pos);
}
return pos;
}
return -1;
}
我需要返回pos,而不是focusNode.getPriority(),在添加當前節點的值后,我只需要將pos加1!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.