二叉树 package 实验二;/** * author:黄良运 * time:11.30 */import java.util.Stack;public class BiTree {BiTreeNode root=null; static int $ = 0; public BiTree() { this.root = null; } public BiTree(AnyType[] preorder) {// "a","b","d",
package 实验二; /** * author:黄良运 * time:11.30 */ import java.util.Stack; public class BiTree { BiTreeNode root=null; static int $ = 0; public BiTree() { this.root = null; } public BiTree(AnyType[] preorder) {// "a","b","d","#","#","#","c","e","#","#","f","#","#" AnyType data = preorder[$++]; if (!data.equals("#")) { root = new BiTreeNode (data); root.lchild = new BiTree (preorder).root; root.rchild = new BiTree (preorder).root; } else { root = null; } } int count = 0; public BiTreeNode create(AnyType[] h) { BiTreeNode root = null; if (count < h.length) { AnyType data = h[count++]; if (!data.equals("#")) { root = new BiTreeNode (data); root.lchild = create(h); root.rchild = create(h); } else { root = null; } } return root; } // static inner class static class BiTreeNode { public AnyType data; public BiTreeNode lchild, rchild; public BiTreeNode() { this(null); } public BiTreeNode(AnyType data) { this(data, null, null); } public BiTreeNode(AnyType data, BiTreeNode lchild, BiTreeNode rchild) { super(); this.data = data; this.lchild = lchild; this.rchild = rchild; } } // non-Recursive traversal by preorder public void preTraverse_nonR(BiTreeNode root) { BiTreeNode T = root; if (T != null) { StackbiTree = new BiTree (a);// ABDEGCFH//DBGEAFHC BiTree biTree2 = new BiTree ();// ABDEGCFH//DBGEAFHC // biTree.root = biTree.createBiTreeByPreorder(a); biTree.preTraverse(biTree.root);// abdcef System.out.println(); biTree.preTraverse_nonR(biTree.root); System.out.println(); biTree.inTraverse(biTree.root);// dbaecf System.out.println(); biTree.inTraverse_nonR(biTree.root); System.out.println(); biTree.postTraverse(biTree.root); System.out.println(); biTree.postTraverse_nonR(biTree.root);// dbefca System.out.println(); System.out.println("深度:" + biTree.getDepth(biTree.root)); System.out.println("叶子:" + biTree.getTreeLeaf(biTree.root)); System.out.println("叶子:" + biTree.leaf(biTree.root)); System.out.println(); BiTreeNode f = biTree2.create(a); biTree2.preTraverse(f); System.out.println(); biTree2.inTraverse(f); } }