我在製作程序時遇到了一個調試問題,關於二叉樹。在我的程序的主要方法中,我使用構造函數創建一個名爲root
的節點,之後我使用getKey()
方法獲取應該引用「root」的「previous
」的密鑰。二叉樹怪異調試
這裏是我的代碼:
/**
* BinaryTreeExample from Internet
* @author xinruchen
*
*/
import java.util.*;
public class BinaryTreeExample
{
private static Node root;
public BinaryTreeExample(int data)
{
root = new Node(data);
}
public void add(Node parent,Node child, String orientation)
{
if(orientation=="left")
{
parent.setLeft(child);
}
else if (orientation=="right")
{
parent.setRight(child);
}
}
public static void main(String ar[])
{
Scanner sc = new Scanner(System.in);
int times = sc.nextInt();
BinaryTreeExample l1=new BinaryTreeExample(3);
Node previous = root;
String direction = "";
System.out.println(previous.getKey());
}
}
class Node {
private int key;
private Node left;
private Node right;
Node (int key) {
this.key = key;
right = null;
left = null;
} // constructor
public void setKey(int key) {
this.key = key;
}
public int getKey() {
return key;
}
public void setLeft(Node l) {
if (left == null) {
this.left = l;
}
else {
left.left = l;
}
}
public Node getLeft() {
return left;
}
public void setRight(Node r) {
if (right == null) {
this.right = r;
}
else {
right.right = r;
}
}
public Node getRight() {
return right;
}
}
如果所有的事情如預期,它應該輸出「3」,但它不是什麼也不輸出。我檢查了我的代碼並遵循了我的代碼流程,但仍然找不到問題所在。請幫助我,謝謝!
糾正語法 –