package Bean;
import java.util.Stack;
public class BinaryTree {
int data;// 根节点树
BinaryTree left;// 左节点
BinaryTree right;// 右节点
public BinaryTree(int data) {
this.data = data;
this.left = null;
this.right = null;
}
public void insert(BinaryTree root, int data) {
if (data > root.data) {
if (root.right == null) {
root.right = new BinaryTree(data);
} else {
this.insert(root.right, data);
}
} else {
if (root.left == null) {
root.left = new BinaryTree(data);
} else {
this.insert(root.left, data);
}
}
}
// 先序递归遍历
public static void preOrder(BinaryTree root) {
if (root == null)
return;
System.out.print(root.data + "---");
if (root.left != null) {
preOrder(root.left);
}
if (root.right != null) {
preOrder(root.right);
}
}
// 先序遍历非递归
public static void preOrder2(BinaryTree root) {
Stack<BinaryTree> s = new Stack<BinaryTree>();
while (root != null || !s.empty()) {
while (root != null) {
System.out.print(root.data + "---");
s.push(root);
root = root.left;
}
if (!s.empty()) {
root = s.pop();
root = root.right;
}
}
}
// 中序递归遍历
public static void InOrder(BinaryTree root) {
if (root == null)
return;
if (root.left != null) {
InOrder(root.left);
}
System.out.print(root.data + "---");
if (root.right != null) {
InOrder(root.right);
}
}
// 中序非递归遍历
public static void InOrder2(BinaryTree root) {
Stack<BinaryTree> s = new Stack<BinaryTree>();
while (root != null || s != null) {
while (root != null) {
s.push(root);
root = root.left;
}
if (s != null) {
root = s.pop();
System.out.print(root.data + "---");
root = root.right;
}
}
}
// 后序递归遍历
public static void forOrder(BinaryTree root) {
if (root == null)
return;
if (root.left != null) {
forOrder(root.left);
}
if (root.right != null) {
forOrder(root.right);
}
System.out.print(root.data + "---");
}
// 后序非递归遍历
public void forOrder2(BinaryTree root) {
int sign = 0;// 得当当前访问节点的次数
Stack stack = new Stack();// 定义一个可以存放TreeNode和Integer的栈
while (root != null || stack != null) {
if (root != null) {// 找最深左子树
stack.push(root);// 将当前节点压入堆栈
stack.push(1);// 并标记当前访问节点的次数
root = root.left;
} else {// 找到最深左子树后
while (!stack.isEmpty()) {
sign = (Integer) stack.pop();// 出栈标记
root = (BinaryTree) stack.pop();// 出栈节点
if (sign == 1) {// 第一次访问节点
stack.push(root);
stack.push(2);
root = root.right;// 将节点指向右子树并开始访问指向右子树的左子树
break;
} else if (sign == 2) {// 当第二次出栈时访问节点
System.out.print(root.data);
root = null;
}
}
}
}
}
public static void main(String[] args) {
int[] arr = { 13, 4, 5, 65, 34, 56, 23 };
BinaryTree root = new BinaryTree(arr[0]);
for (int i = 1; i < arr.length; i++) {
root.insert(root, arr[i]);
}
forOrder(root);
}
}
二叉树遍历(递归和非递归)
最新推荐文章于 2022-02-25 21:57:51 发布