


運行的結果是:確實列印了,,但是報錯

代碼如下:
結點類:
public class BinTrNode {
public int data;
BinTrNode Left;
BinTrNode right;
public BinTrNode(int data,BinTrNode left,BinTrNode right){//注意創建結點是建構式!!!
this.data = data;
this.Left = left;
this.right = right;
}
}
主函式:
import java.util.Stack;
import sun.print.resources.serviceui;
/** 1
* 2 3
* 4 5 n 10
* 7 8 n 9 n 11
*/
public class BinTrtest {
static BinTrNode J = new BinTrNode(11, null, null);
static BinTrNode I = new BinTrNode(10, null, J);
static BinTrNode H = new BinTrNode(9, null, null);
static BinTrNode G = new BinTrNode(8, null, null);
static BinTrNode F = new BinTrNode(7, null, null);
static BinTrNode E = new BinTrNode(5, H, null);
static BinTrNode D = new BinTrNode(4, F, G);
static BinTrNode C = new BinTrNode(3, null, I);
static BinTrNode B = new BinTrNode(2, D, E);
static BinTrNode A = new BinTrNode(1, B, C);
/**
* 非遞回實作中序遍歷思路: 1、拿到一個節點,push操作,并去遍歷其左子樹
* 2、左子樹遍歷結束后,pop堆疊頂元素,并列印
* 3、遍歷其右子樹
*/
//中序遍歷
public static void Inroottravelsal(BinTrNode b){
Stack<BinTrNode> stack = new Stack<BinTrNode>();
BinTrNode node =b;
while(node != null || stack != null){
while(node != null){
stack.push(node);
node = node.Left;
}
if(stack != null){
node = stack.pop();
System.out.print(node.data);
node = node.right;
}
}
}
public static void main(String[] args) {
//非遞回中序
System.out.println(" ");
Inroottravelsal(A);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/84656.html
標籤:基礎類
