二叉树三种遍历:
前序遍历的顺序是根节点、左节点、右节点
/**
* 前序遍历
*/
public void preOrder() {
if (this.root != null) {
this.root.preOrder();
} else {
System.out.println("当前二叉树为空无法遍历");
}
}
/**
* 此处为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.root != null) {
this.root.infixOrder();
} else {
System.out.println("当前二叉树为空无法遍历");
}
}
/**
* 此处为Node的方法
* 中序遍历
*/
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.root != null) {
this.root.postOrder();
} else {
System.out.println("当前二叉树为空无法遍历");
}
}
/**
* 此处为Node的方法
* 后序遍历
*/
public void postOrder() {
if (this.left != null) {
this.left.postOrder();
}
if (this.right != null) {
this.right.postOrder();
}
System.out.println(this);
}
二叉树三种查找:
查找方式和遍历一样
前序查找:
/**
* 前序查找
* @param no 查找的id
* @return 找到返回node,反之为null
*/
public HeroNode preOrderSearch(int no) {
if (root != null) {
return root.preOrderSearch(no);
} else {
return null;
}
}
/**
* 前序查找
* @param no 查找的编号
* @return 找到返回node,反之为null
*/
public HeroNode preOrderSearch(int no) {
HeroNode resNode = null;
if (this.no == no) {
return this;
}
if (this.left != null) {
resNode = this.left.preOrderSearch(no);
}
if (resNode != null) {
return resNode;
}
if (this.right != null) {
resNode = this.right.preOrderSearch(no);
}
return resNode;
}
中序查找:
/**
* 中序查找
* @param no 查找的id
* @return 找到返回node,反之为null
*/
public HeroNode infixOrderSearch(int no) {
if (root != null) {
return root.infixOrderSearch(no);
} else {
return null;
}
}
/**
* 中序查找
* @param no 查找的编号
* @return 找到返回node,反之为null
*/
public HeroNode infixOrderSearch(int no) {
HeroNode resNode = null;
if (this.left != null) {
resNode = this.left.infixOrderSearch(no);
}
if (resNode != null) {
return resNode;
}
if (this.no == no) {
return this;
}
if (this.right != null) {
resNode = this.right.infixOrderSearch(no);
}
return resNode;
}
后序查找:
/**
* 后序查找
* @param no 查找的id
* @return 找到返回node,反之为null
*/
public HeroNode postOrderSearch(int no) {
if (root != null) {
return root.postOrderSearch(no);
} else {
return null;
}
}
/**
* 后序查找
* @param no 查找的编号
* @return 找到返回node,反之为null
*/
public HeroNode postOrderSearch(int no) {
HeroNode resNode = null;
if (this.left != null) {
resNode = this.left.postOrderSearch(no);
}
if (resNode != null) {
return resNode;
}
if (this.right != null) {
resNode = this.right.postOrderSearch(no);
}
if (resNode != null) {
return resNode;
}
if (this.no == no) {
return this;
}
return resNode;
}