文章目录
二叉树结构定义
// 定义二叉树的形式
public class Node {
public int value;
public Node left;
public Node right;
public Node(int value) {
this.value = value;
}
}
二叉树打印所有节点
前序,中序,后序
递归方法
//前序递归
public void preOrder(Node head) {
if(head == null) return;
System.out.print(head.value + " ");
preOrder(head.left);
preOrder(head.right);
}
//中序递归
public void inOrder(Node head) {
if(head == null) return;
inOrder(head.left);
System.out.print(head.value + " ");
inOrder(head.right);
}
//后序递归
public void postOrder(Node head) {
if(head == null) return;
postOrder(head.left);
postOrder(head.right);
System.out.print(head.value + " ");
}
非递归方法
前序:
利用stack,先压根节点。
每次弹出栈顶并打印,栈顶元素如果有右节点压右节点,有左节点压左节点。循环直到栈空。
public void preOrder(Node head) {
if(head != null) {
Stack<Node> stack = new Stack<>();
stack.push(head);
while(!stack.isEmpty() {
head = stack.pop();
System.out.print(head.value + " ");
if(head.right != null) stack.push(head.right);
if(head.left != null) stack.push(head.left);
}
}
}
中序:
当前节点为空,从栈中拿一个打印,向右查找,如果不为空,压入栈,向左查找。(先把节点的左边界都压进去)
public void inOrder(Node head) {
if(head != null) {
Stack<Node> stack = new Stack<>();
while(!stack.isEmpty() || head != null) {
if(head != null) {
stack.push(head);
head = head.left;
} else {
head = stack.pop();
System.out