1、前中后序遍历
(1)Node结点代码
//前序遍历
public void preOrder(){
System.out.println(this);
if(this.left != null){
this.left.preOrder();
}
if(this.right!=null){
this.right.preOrder();
}
}
//中序遍历
public void infixOrder(){
if(this.left != null){
this.left.infixOrder();
}
System.out.println(this);
if(this.right!=null){
this.right.infixOrder();
}
}
//后序遍历
public void postOrder(){
if(this.left != null){
this.left.postOrder();
}
if(this.right != null){
this.right.postOrder();
}
System.out.println(this);
}
(2)BinaryTree代码
//前序遍历
public void preOrder(){
if(this.root!=null){
this.root.preOrder();
}else{
System.out.println("空的二叉树");
}
}
//中序遍历
public void infixOrder(){
if(this.root!=null){
this.root.infixOrder();
}else{
System.out.println("空的二叉树");
}
}
//后序遍历
public void postOrder(){
if(this.root!=null){
this.root.postOrder();
}else{
System.out.println("空的二叉树");
}
}
2、前中后序查找
(1)Node结点代码
public Node preOrderSearch(String item){
Node res=null; //每次进行递归,没有找到元素的返回值
if(this.item.equals(item)){
return this; //每次进行递归,找到元素的返回值
}
if(this.left!=null){
res=this.left.preOrderSearch(item);
}
//找到必须立即返回
if(res!=null){
return res;
}
if(this.right!=null){
res=this.right.preOrderSearch(item);
}
return res;
}
public Node infixOrderSearch(String item){
Node res=null;
if(this.left != null){
res=this.left.infixOrderSearch(item);
}
if(res!=null){
return res;
}
//前边两个if都没有执行,说明已经找到了最终的节点
if(this.item.equals(item)){
return this;
}
if(this.right!=null){
res=this.right.infixOrderSearch(item);
}
return res;
}
public Node postOrderSearch(String item){
Node res=null;
if(this.left != null){
res=this.left.postOrderSearch(item);
}
if(res!=null){//说明左子树找到
return res;
}
if(this.right!=null){
res=this.right.postOrderSearch(item);
}
if(res!=null){//说明右子树找到
return res;
}
if(this.item.equals(item)){
return this;
}
return res;
}
(2)BinaryTree代码
public Node preOrderSearch(String item){
if(this.root != null){
return this.root.preOrderSearch(item);
}else{
return null;
}
}