import java.util.*;
class Node{
char value;
Node left;
Node right;
Node(){
}
Node (char value){
this.value=value;
}
}
public class Main{
//核心代碼 我們看到
public static int i=0;
public static Node buildTree(String str){
Node root=null;
//int i=0;如果說我們i在這裏進行定義,可以發現這個是屬於在一個循環的內部,
//只要我們一進行遞歸呢麼這個i又會爲0。
if(str.charAt(i)!='#'){
root=new Node(str.charAt(i));
i++;
root.left=buildTree(str);
root.right=buildTree(str);
}else{
i++;
}
return root;
}
//中序遍歷
public static void inOrderTraversal(Node root){
if (root==null){
return;
}
inOrderTraversal(root.left);
System.out.print(root.value+" ");
inOrderTraversal(root.right);
}
public static void main(String []args){
Scanner scan=new Scanner(System.in);
String str=scan.nextLine();
//到這步我們是定義一個root去接收我們創建的樹
Node root=buildTree(str);
//我們調用中序遍歷去打印
inOrderTraversal(root);
}
}
二叉樹的構建和遍歷
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.