二叉树的遍历是利用节点中的递归方法实现的
三种遍历的顺序也很好记,记住一个其他的就记住了,遍历从根节点开始,“中”代表先大于递归中的this对象。
前序遍历:中->左->右 1,2,3,4
中序遍历:左->中->右 2,1,4,3
后序遍历:左->右->中 2,4,3,1
什么序遍历”中“就放在什么位置上。
节点:
static class Node{
private int no;
private String name;
private Node left;
private Node right;
public Node(int no, String name) {
this.no = no;
this.name = name;
}
}
节点中的方法
由于是递归,每个方法里只有一个打印语句就够,因为递归保证了每个节点都会被执行sout(this)方法。如果一个节点是叶子节点,它打印完自己向上一层返回。
/**
* 前序遍历
*/
public void PreOrder(){
System.out.println(this);
if (this.left != null){
this.left.PreOrder();
}
if (this.right != null){
this.right.PreOrder();
}
}
/**
* 中序遍历
* @return
*/
public void infixOrder(){
if (this.left != null){
this.left.infixOrder();
}
System.out.println(this);
if (this.right != null){
this.right.infixOrder();
}
}
/**
* 后序遍历
* @return
*/
public void postOrder(){
if (this.left != null){
this.left.postOrder();
}
if (this.right != null){
this.right.postOrder();
}
System.out.println(this);
}
最终调用这个方法的是根节点,此方法在二叉树的类中,只需要调用即可。
static class Tree{
private Node root;
public void setRoot(Node root) {
this.root = root;
}
/**
* 前序遍历
*/
public void preOrder(){
if (this.root != null){
root.PreOrder();
}else {
System.out.println("空树!");
}
}
}
查找和遍历的逻辑是一样的,最后用根节点调用
/**
* 中序查找
* @param no
* @return
*/
public Node infixSearch(int no){
Node resNode = null;
if (this.left != null)
resNode = this.left.infixSearch(no);
if (resNode != null)
return resNode;
else if (this.no == no)
return this;
if (this.right != null)
resNode = this.right.infixSearch(no);
return resNode;
}
测试**
public static void main(String[] args) {
Tree tree = new Tree();
Node root = new Node(1,"a");
Node n2 = new Node(2,"b");
Node n3 = new Node(3,"c");
Node n4 = new Node(4,"d");
root.setLeft(n2);
root.setRight(n3);
n3.setLeft(n4);
tree.setRoot(root);
tree.infixOrder();
}
Node{no=2, name='b'}
Node{no=1, name='a'}
Node{no=4, name='d'}
Node{no=3, name='c'}