根据前序、中序、后序遍历方法,我们可以通过这种方式来查找节点。查找方法与遍历类似。
前序查找先查找根节点,再查找左子节点与右子节点;中序查找先查找左子节点、再查找根节点与右子节点;后序查找先查找左子节点与右子节点,再查找根节点。
public class Main {
public static void main(String[] args) {
Node node1 = new Node(1, "Amy");
Node node2 = new Node(2, "Bob");
Node node3 = new Node(3, "Candy");
Node node4 = new Node(4, "Doff");
Node node5 = new Node(5, "Emma");
BinaryTree tree = new BinaryTree();
tree.setRoot(node1);
node1.setLeft(node2);
node1.setRight(node3);
node3.setLeft(node5);
node3.setRight(node4);
Node resNode = null;
System.out.println("前序查找第5个节点");
resNode = tree.preOrderSearch(5);
if (resNode != null) {
System.out.println(resNode);
} else {
System.out.println("查找不到该节点");
}
System.out.println("中序查找第5个节点");
resNode = tree.infixOrderSearch(5);
if (resNode != null) {
System.out.println(resNode);
} else {
System.out.println("查找不到该节点");
}
System.out.println("后序查找第5个节点");
resNode = tree.postOrderSearch(5);
if (resNode != null) {
System.out.println(resNode);
} else {
System.out.println("查找不到该节点");
}
}
}
//节点
class Node {
private int id;
private String name;
Node left;
Node right;
public Node(int ID, String na) {
this.id = ID;
this.name = na;
}
public void setLeft(Node left) {
this.left = left;
}
public void setRight(Node right) {
this.right = right;
}
@Override
public String toString() {
return "Node{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
//前序查找
public Node preOrderSearch(int id) {
System.out.println("前序进行比较");
if (this.id == id) {
return this;
}
Node node = null;
if (this.left != null) {
node = this.left.preOrderSearch(id);
}
if (node != null) {
return node;
}
if (this.right != null) {
node = this.right.preOrderSearch(id);
}
return node;
}
//中序查找
public Node infixOrderSearch(int id) {
Node node = null;
if (this.left != null) {
node = this.left.infixOrderSearch(id);
}
if (node != null) {
return node;
}
System.out.println("中序进行比较");
if (this.id == id) {
return this;
}
if (this.right != null) {
node = this.right.infixOrderSearch(id);
}
return node;
}
//后序查找
public Node postOrderSearch(int id) {
Node node = null;
if (this.left != null) {
node = this.left.postOrderSearch(id);
}
if (node != null) {
return node;
}
if (this.right != null) {
node = this.right.postOrderSearch(id);
}
if (node != null) {
return node;
}
System.out.println("后序进行比较");
if (this.id == id) {
return this;
}
return node;
}
}
//二叉树
class BinaryTree {
private Node root;
public void setRoot(Node root) {
this.root = root;
}
//前序查找
public Node preOrderSearch(int id) {
if (this.root != null) {
return this.root.preOrderSearch(id);
} else {
return null;
}
}
//中序查找
public Node infixOrderSearch(int id) {
if (this.root != null) {
return this.root.infixOrderSearch(id);
} else {
return null;
}
}
//后序查找
public Node postOrderSearch(int id) {
if (this.root != null) {
return this.root.postOrderSearch(id);
} else {
return null;
}
}
}
前序查找第5个节点
前序进行比较
前序进行比较
前序进行比较
前序进行比较
Node{id=5, name='Emma'}
中序查找第5个节点
中序进行比较
中序进行比较
中序进行比较
Node{id=5, name='Emma'}
后序查找第5个节点
后序进行比较
后序进行比较
Node{id=5, name='Emma'}