标签:col 二叉树 非递归 empty 实现 his static 后序遍历 一个栈
构造二叉树:
class Node{ public String value; public Node left; public Node right; public Node(String value) { this.value = value; } }
递归版前序遍历:
public static void preOrder(Node head){ if(head != null){ System.out.print(head.value + " "); preOrder(head.left); preOrder(head.right); } }
递归版中序遍历:
public static void inOrder(Node head){ if(head != null){ inOrder(head.left); System.out.print(head.value + " "); inOrder(head.right); } }
递归版后序遍历:
public static void posOrder(Node head){ if(head != null){ posOrder(head.left); posOrder(head.right); System.out.print(head.value + " "); } }
非递归版前序遍历:
public static void preOrder(Node head){ if(head != null){ Stack<Node> stack = new Stack<>(); stack.push(head); while(!stack.isEmpty()){ Node pop = stack.pop(); System.out.print(pop.value + " "); if(pop.right != null) stack.push(pop.right); if(pop.left != null) stack.push(pop.left); } } }
非递归版中序遍历:
public static 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.print(head.value + " "); head = head.right; } } } }
非递归版后序遍历:
public static void postOrder(Node head){ if(head != null){ Stack<Node> stack1 = new Stack<>(); Stack<Node> stack2 = new Stack<>(); stack1.push(head); while(!stack1.isEmpty()){ Node pop = stack1.pop(); stack2.push(pop); if(pop.left != null){ stack1.push(pop.left); } if(pop.right != null){ stack1.push(pop.right); } } while(!stack2.isEmpty()){ System.out.print(stack2.pop().value + " "); } } }
这里用了两个栈,其实一个栈也能实现,这里这样做是因为可以和前序遍历对比着记,比较容易。
标签:col 二叉树 非递归 empty 实现 his static 后序遍历 一个栈
原文地址:https://www.cnblogs.com/DarrenChan/p/8798412.html