JAVA实现树的遍历
注:主要是指二叉树 D是指根节点,L是左节点,R是右节点
前序遍历
DRL (先取根节点,再取左节点,最后取右节点)
结果:
public void frontShow(){
System.out.print(this.getValue()+"\t");
if(this.treeLeftNode!=null){
this.treeLeftNode.frontShow();
}
if(this.treeRightNode!=null){
this.treeRightNode.frontShow();
}
}
中序遍历
LDR(先取左节点,再取根点,最后取右节点)
结果:
public void midShow(){
if(this.treeLeftNode!=null){
this.treeLeftNode.midShow();
}
System.out.print(this.getValue()+"\t");
if(this.treeRightNode!=null){
this.treeRightNode.midShow();
}
}
后序遍历
LRD(先取左节点,再取右节点,最后取根节点)
结果:
public void finalShow() {
if (this.treeLeftNode != null) {
this.treeLeftNode.finalShow();
}
if (this.treeRightNode != null) {
this.treeRightNode.finalShow();
}
System.out.print(this.getValue() + "\t");
}
注:每到一个新的节点,就要用遍历的思想进行判断取哪个节点,这可以用递归的思想处理
使用遍历的思想实现树节点的查找
前序查找
public TreeNode frontSearch(int i) {
TreeNode target = null;
if (i == this.getValue()) {
return this;
} else {
//查询左节点
if (this.treeLeftNode != null) {
target = treeLeftNode.frontSearch(i);
}
//如果左节点找到了就不用遍历右节点
if (target != null) {
return target;
}
//查询右节点
if (this.treeRightNode != null) {
target = treeRightNode.frontSearch(i);
}
}
return target;
}
中序查找
//中序查找
public TreeNode midSearch(int i) {
TreeNode target = null;
if (this.treeLeftNode != null) {
target = this.treeLeftNode.midSearch(i);
}
if (target != null) {
return target;
}
if (this.getValue() == i) {
return this;
} else {
if (this.treeRightNode != null) {
target = this.treeRightNode.midSearch(i);
}
return target;
}
}
后序查找
//后续查找
public TreeNode afterSearch(int i){
TreeNode target = null;
if(this.treeLeftNode!=null){
target = this.treeLeftNode.afterSearch(i);
}
if(target!=null){
return target;
}
if(this.treeRightNode!=null){
target = this.treeRightNode.afterSearch(i);
}
if(this.getValue()==i){
return this;
}
return target;
}