此时有这样一棵树,其先序遍历:ABCDEFGH;中序遍历:CBEDFAGH;后序遍历:CEFDBHGA;想要以输入结点的方式来创建树。可以考虑一个节点创建成功在创建其左右结点,若其左右结点为空,则返回至上一个结点继续创建,直到创建完毕。
创建树的结点:
class BNode{ private BNode leftChild; private BNode rightChild; private char data; public BNode() { } public BNode(char data){ this.data = data; } public BNode(BNode leftChild,BNode rightChild,char data){ this.leftChild = leftChild; this.rightChild = rightChild; this.data = data; } public BNode getLeftChild() { return leftChild; } public void setLeftChild(BNode leftChild) { this.leftChild = leftChild; } public BNode getRightChild() { return rightChild; } public void setRightChild(BNode rightChild) { this.rightChild = rightChild; } public char getData() { return data; } public void setData(char data) { this.data = data; } }
创建树以及遍历树:
class BTree{ private BNode root ; private int i ; private String str; //输入字符串 private Scanner scanner; public BTree(){ this.root = null; this.i = 0; this.str = null; this.scanner = new Scanner(System.in); } public void PreOrder() { //先序遍历 System.out.println("前序遍历: "); PreOrder(root); System.out.println(); } private void PreOrder(BNode root) { if(root != null){ System.out.print(root.getData()+" "); PreOrder(root.getLeftChild()); PreOrder(root.getRightChild()); } } public void InOrder() { //中序遍历 System.out.println("中序遍历: "); InOrder(root); System.out.println(); } private void InOrder(BNode root) { if(root != null){ InOrder(root.getLeftChild()); System.out.print(root.getData()+" "); InOrder(root.getRightChild()); } } public void PastOrder() { //后序遍历 System.out.println("后序遍历: "); PastOrder(root); System.out.println(); } private void PastOrder(BNode root) { if(root != null){ PastOrder(root.getLeftChild()); PastOrder(root.getRightChild()); System.out.print(root.getData()+" "); } } public void CreatTree(){ //创建树 (根据先序遍历顺序创建) root = CreatTreeA(); } private void add(){ i +=1; } public void SysIn(){ str = scanner.next(); } private BNode CreatTreeA(){ char a ; BNode root = null; //1.读入元素 a = str.charAt(i); add(); //如果不等于'#',创建该节点,并且创建其左右孩子 if (a != '#') { root = new BNode(a); root.setLeftChild(CreatTreeA()); root.setRightChild(CreatTreeA()); } // 否则,return root。 return root; } }
public class BinaryTreeDemo { public static void main(String[] args) { BTree bTree = new BTree(); System.out.println("请输入创建树的节点:"); bTree.SysIn(); //输入ABC##DE##F##G#H## bTree.CreatTree(); //创建树 //遍历 bTree.PreOrder(); bTree.InOrder(); bTree.PastOrder(); } }
其中#表示root节点的左右孩子。
来源:https://www.cnblogs.com/128-cdy/p/12535792.html