我試圖爲我正在開發的AI遞歸地構建二叉樹。 我嘗試構建一棵樹,但所有內容都返回null。語言是Java,我正在使用Eclipse。另外,如果這意味着什麼,我在Mac上。該樹應作爲二叉樹返回,節點實例化但沒有任何內容。爲節點返回空值的二叉樹
public class DecisionTree {
//build a generic, empty, tree
//building binary
Root r = new Root();
public void build() //ok
{
Node lhs = new Node();
Node rhs = new Node();
lhs = new Node();
rhs = new Node();
r.lhs = lhs;
r.rhs = rhs;
lhs.parent = r;
rhs.parent = r;
builtRecursion(lhs, 1);
builtRecursion(rhs, 1);
outputTree();
int ctr = 1; //levels of tree
}
public int builtRecursion(Node n, int ctr)
{
Node lhs = new Node();
Node rhs = new Node();
ctr++;
System.out.println("built recursion ctr is " + ctr);
if (ctr > 10)
{
//leaf node
Behaviors behavior = new Behaviors();
Node node = behavior;
n.b = behavior;
return 0;
}
n.lhs = lhs;
n.rhs = rhs;
lhs.parent = n;
rhs.parent = n;
builtRecursion(lhs, ctr);
builtRecursion(rhs, ctr);
return ctr;
}
public void outputTree()
{
if (r != null)
{
System.out.println("Root");
}
outputTreeRecursive(r);
}
public void outputTreeRecursive(Node n)
{
if (n.lhs != null)
{
System.out.println("------------------");
System.out.println("LHS");
outputTreeRecursive(n.lhs);
}
else { System.out.println("LHS is null");}
if (n.rhs != null)
{
System.out.println("-----------------");
System.out.println("RHS");
outputTreeRecursive(n.rhs);
}
else { System.out.println("RHS is null");}
System.out.println("-----------------");
}
}
ROOT班組長
package FLINCH;
public class Root extends Node {
Node lhs = new Node();
Node rhs = new Node();
}
節點類
package FLINCH;
import java.util.ArrayList;
import java.util.LinkedList;
public class Node {
Node lhs = null;
Node rhs = null;
Node parent = null;
Decider d = new Decider(this);
Behaviors b = null;
public LinkedList getSuccessors()
{
LinkedList list = new LinkedList();
list.add(lhs);
list.add(rhs);
return list;
}
}
OUTPUT
GetAction Running
Iterating through open list
Size of open list is 1
Peeked openLIst size is 1
Peeking throguh open list
Popping Open List
LHS is null
RHS is null
Number of children is 2
Children equals 2
Decider childrens loop
Child node is null
Iterating through children
Exception in thread "main" java.lang.NullPointerException
at FLINCH.A_Star_Search.search3(A_Star_Search.java:81)
at FLINCH.Soldier.search_behavior(Soldier.java:28)
at FLINCH.Main.getAction(Main.java:54)
at tests.GameVisualSimulationTest.main(GameVisualSimulationTest.java:52)
我希望這有助於...
只有葉子左,右後代應打印成'null'。分享你的輸出,以及你如何定義'Node'和'Root'(我認爲'Root'擴展了'Node',一個帶有3個變量的類 - 'lhs','rhs'和'parent'?) –
你的意思是「一切都回來了」?你的算法看起來很好,當我嘗試它時(深度小於10),輸出結果就是我所期望的。我建議你用10代替2或3來嘗試,然後發佈輸出並解釋輸出結果不是你所期望的。 – ajb
ajb:將二叉樹實例化到某個級別。當我嘗試遍歷它時,我從根開始,然後轉到左側和右側,但是這些值爲空,當它們應該是Node對象的實例等等,直到它到達樹葉。我試着用值2到10來得到相同的結果 –