package tree;
/**
* @author taoke
* @desc 二叉树
* @email 1504806660@qq.com
* @date 2022/1/10
*/
public class BinaryTree {
public static void main(String[] args) {
//初始化二叉树
Node root = new Node(1, "宋江");
Node node2 = new Node(2, "吴用");
Node node3 = new Node(3, "卢俊义");
Node node4 = new Node(4, "林冲");
//将树关联起来
root.left = node2;
root.right = node3;
node3.right = node4;
//前序遍历
root.preorder();//结果是1234
//中序遍历
root.inorder();//结果是2134
//后序遍历
root.postorder();//结果是2431
//前序查找
System.out.println(root.preorderSearch(3));
//中序查找
System.out.println(root.inorderSearch(3));
//后序查找
System.out.println(root.postorderSearch(3));
}
static class Node {
public int id;
public String name;
public Node left;
public Node right;
public Node(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Node{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
/**
* 前序遍历
* 遍历顺序是根节点 root节点->左节点->右节点
*/
public void preorder() {
//当前节点
System.out.println(this);
//左节点不为空,递归遍历
if (this.left != null) {
this.left.preorder();
}
//右节点不为空,递归遍历
if (this.right != null) {
this.right.preorder();
}
}
/**
* 中序遍历
* 遍历顺序是根节点 左节点->root节点->右节点
*/
public void inorder() {
//左节点不为空,递归遍历
if (this.left != null) {
this.left.inorder();
}
//当前节点
System.out.println(this);
//右节点不为空,递归遍历
if (this.right != null) {
this.right.inorder();
}
}
/**
* 后序遍历
* 遍历顺序是根节点 左节点->右节点->root节点
*/
public void postorder() {
//左节点不为空,递归遍历
if (this.left != null) {
this.left.postorder();
}
//右节点不为空,递归遍历
if (this.right != null) {
this.right.postorder();
}
//当前节点
System.out.println(this);
}
/**
* 前序查找
*
* @param number 待查找索引
* @return 查找结果
*/
public Node preorderSearch(int number) {
System.out.println("查找中=== " + this);
if (this.id == number) {
return this;
}
Node temp;
if (this.left != null) {
temp = this.left.preorderSearch(number);
if (temp != null) {
return temp;
}
}
if (this.right != null) {
temp = this.right.preorderSearch(number);
return temp;
}
return null;
}
/**
* 中序查找
*
* @param number 带查找索引
* @return 查找结果
*/
public Node inorderSearch(int number) {
Node temp;
if (this.left != null) {
temp = this.left.inorderSearch(number);
if (temp != null) {
return temp;
}
}
if (this.id == number) {
return this;
}
if (this.right != null) {
temp = this.right.inorderSearch(number);
return temp;
}
return null;
}
/**
* 后序查找
*
* @param number 带查找索引
* @return 查找结果
*/
public Node postorderSearch(int number) {
Node temp;
if (this.left != null) {
temp = this.left.postorderSearch(number);
if (temp != null) {
return temp;
}
}
if (this.right != null) {
temp = this.right.postorderSearch(number);
if (temp != null) {
return temp;
}
}
if (this.id == number) {
return this;
}
return null;
}
}
}
数据结构与算法-二叉树
于 2022-01-10 15:09:19 首次发布