二叉树结构:
public static class TreeNode{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
先序递归遍历:
public static void preOrder(TreeNode root){
if (root == null){
return;
}
System.out.print(root.val + " ");
preOrder(root.left);
preOrder(root.right);
}
中序递归遍历:
public static void inOrder(TreeNode root){
if (root == null){
return;
}
inOrder(root.left);
System.out.print(root.val + " ");
inOrder(root.right);
}
后序递归遍历:
public static void posOrder(TreeNode root){
if (root == null){
return;
}
posOrder(root.left);
posOrder(root.right);
System.out.print(root.val + " ");
}
用栈改造先序递归遍历:
//用栈改造先序递归方法
public static void preOrderUnRecur(TreeNode root){
if (root == null){
return;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()){
TreeNode node = stack.pop();
System.out.print(node.val + " ");
//栈是先进后出 想要先打印左孩子 就要保证左孩子最后入栈
if (node.right != null){
stack.push(node.right);
}
if (node.left != null){
stack.push(node.left);
}
}
}
用栈改造中序递归遍历:
//用栈改造中序递归方法
public static void inOrderUnRecur(TreeNode root){
if (root == null){
return;
}
Stack<TreeNode> stack = new Stack<>();
while (!stack.isEmpty() || root != null){
if (root != null){
stack.push(root);
root = root.left;
}else {
root = stack.pop();
System.out.print(root.val + " ");
root = root.right;
}
}
}
用栈改造后序递归遍历:
//用栈改造后序递归方法
public static void posOrderUnRecur(TreeNode root){
if (root == null){
return;
}
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
stack1.push(root);
while (!stack1.isEmpty()){
TreeNode node = stack1.pop();
stack2.push(node);
if (node.left != null){
stack1.push(node.left);
}
if (node.right != null){
stack1.push(node.right);
}
}
while (!stack2.isEmpty()){
TreeNode node = stack2.pop();
System.out.print(node.val + " ");
}
}
提供一颗二叉树:
public static void main(String[] args) {
TreeNode head = new TreeNode(1);
head.left = new TreeNode(2);
head.right = new TreeNode(3);
head.left.left = new TreeNode(4);
head.left.right = new TreeNode(5);
head.right.left = new TreeNode(6);
head.right.right = new TreeNode(7);
preOrder(head);
System.out.println();
System.out.println("先序遍历递归版");
inOrder(head);
System.out.println();
System.out.println("中序遍历递归版");
posOrder(head);
System.out.println();
System.out.println("后序遍历递归版");
preOrderUnRecur(head);
System.out.println();
System.out.println("先序遍历栈版");
posOrderUnRecur(head);
System.out.println();
System.out.println("后序遍历栈版");
inOrderUnRecur(head);
System.out.println();
System.out.println("中序遍历栈版");
}