/**
*java实现二叉树
*/
public class BiTree {
Scanner scan=new Scanner(System.in);
/**
* 定义树的节点类,可以单独创建该类
* */
class Node{
private char data;
private Node lchild,rchild;
public Node(){
}
public void setData(char data){
this.data=data;
}
}
/**
* 空节点用#表示
*
* */
public Node createBiTree(){
Node T = null;
char ch;
ch=scan.next().charAt(0);
if(ch=='#'){
T=null;
}
else{
T=new Node();
T.setData(ch);
T.lchild=createBiTree();
T.rchild=createBiTree();
}
return T;
}
public void preSearch(Node root){
if(root!=null){
System.out.print(root.data+" ");
preSearch(root.lchild);
preSearch(root.rchild);
}
}
public void preNoRecursion(Node root){
Stack<Node>nodeStack=new Stack<Node>();
Node tree=root;
while(tree!=null||nodeStack.size()>0){
while(tree!=null){
System.out.print(tree.data+" ");
nodeStack.push(tree);
tree=tree.lchild;
}
if(nodeStack.size()>0){
tree=nodeStack.pop();
tree=tree.rchild;
}
}
}
public void inSearch(Node root){
if(root!=null){
inSearch(root.lchild);
System.out.print(root.data+" ");
inSearch(root.rchild);
}
}
public void inNoRecursion(Node root){
Stack<Node>nodeStack=new Stack<Node>();
Node tree=root;
while(tree!=null||nodeStack.size()>0){
while(tree!=null){
nodeStack.push(tree);
tree=tree.lchild;
}
if(nodeStack.size()>0){
tree=nodeStack.pop();
System.out.print(tree.data+" ");
tree=tree.rchild;
}
}
}
public void postSearch(Node root){
if(root!=null){
postSearch(root.lchild);
postSearch(root.rchild);
System.out.print(root.data+" ");
}
}
public void postNoRecursion(Node root){
Stack<Node>treeStack=new Stack<BiTree.Node>();
Node tree=root;
Node node=null;
while(tree!=null){
for(;tree.lchild!=null;tree=tree.lchild){
treeStack.push(tree);
}
while((tree!=null)&&(tree.rchild==null||tree.rchild==node)){
System.out.print(tree.data+" ");
node=tree;
if(treeStack.isEmpty()){
return;
}
tree=treeStack.pop();
}
treeStack.push(tree);
tree=tree.rchild;
}
}
/**
* 求节点个数
* */
public int nodeSize(Node root){
if(root==null){
return 0;
}else{
return 1+nodeSize(root.lchild)+nodeSize(root.rchild);
}
}
public int height(Node root){
if(root==null){
return 0;
}else{
int left=height(root.lchild);
int right=height(root.rchild);
return left<right?(right+1):(left+1);
}
}
public static void main(String[]args){
BiTree tree=new BiTree();
Node root=tree.createBiTree();
System.out.print("前序为:");
tree.preSearch(root);
System.out.println();
System.out.print("非递归前序为:");
tree.preNoRecursion(root);
System.out.println();
System.out.print("中序为:");
tree.inSearch(root);
System.out.println();
System.out.print("非递归中序为:");
tree.inNoRecursion(root);
System.out.println();
System.out.print("后序为:");
tree.postSearch(root);
System.out.println();
System.out.print("非递归后序为:");
tree.postNoRecursion(root);
System.out.println();
}
}