前序遍历:1 2 4 5 3 6 7
中序遍历:4 2 5 1 6 3 7
后序遍历:4 5 2 6 7 3 1
二叉树遍历
public class TreeNode {
//根节点值
private int value;
//左节点
private TreeNode leftNode;
//右节点
private TreeNode rightNode;
public TreeNode(int value) {
this.value = value;
}
public void setValue(int value) {
this.value = value;
}
public void setLeftNode(TreeNode leftNode) {
this.leftNode = leftNode;
}
public void setRightNode(TreeNode rightNode) {
this.rightNode = rightNode;
}
//前序遍历
public void frontNode(TreeNode node) {
System.out.println(node.value);
if (node.leftNode != null) {
frontNode(node.leftNode);
}
if (node.rightNode != null) {
frontNode(node.rightNode);
}
}
//中序遍历
public void midNode(TreeNode node) {
if (node.leftNode != null) {
midNode(node.leftNode);
}
System.out.println(node.value);
if (node.rightNode != null) {
midNode(node.rightNode);
}
}
//后序遍历
public void afterNode(TreeNode node) {
if (node.leftNode != null) {
afterNode(node.leftNode);
}
if (node.rightNode != null) {
afterNode(node.rightNode);
}
System.out.println(node.value);
}
}
二叉树前序查找
//前序查找
public TreeNode fontSearch(int i) {
TreeNode node = null;
if (i == this.value) {
return this;
}
if (this.leftNode != null) {
node = this.leftNode.fontSearch(i);
}
if (this.rightNode != null && node==null) {
node = this.rightNode.fontSearch(i);
}
return node;
}
删除节点
//删除节点(前序遍历)
public void deleteNode(int i) {
TreeNode treeNode = this;
if (this.leftNode != null && this.leftNode.value == i) {
this.leftNode = null;
return;
} else {
this.leftNode.deleteNode(i);
}
if (this.rightNode != null && this.rightNode.value == i) {
this.rightNode = null;
return;
} else {
this.rightNode.deleteNode(i);
}
}