分别用递归和非递归方式实现二叉树先序、中序和后序遍历
用递归和非递归方式,分别按照二叉树先序、中序和后序打印所有的节点。我们约定:先序遍历顺序 为根、左、右;中序遍历顺序为左、根、右;后序遍历顺序为左、右、根
后序遍历:头节点入栈,用一个变量表示栈顶
用递归和非递归方式,分别按照二叉树先序、中序和后序打印所有的节点。我们约定:先序遍历顺序 为根、左、右;中序遍历顺序为左、根、右;后序遍历顺序为左、右、根
先序遍历:建立一个栈,头节点入栈,将其出栈并打印,之后再依次将其右子节点入栈,左子节点入栈,栈顶节点出栈并打印,再依次将其右子节点和左子节点入栈,再将栈顶节点出栈并打印,递归实现。
public static void preOrderUnRecur(Node head){
System.out.println("PreOrder:");
if(head != null){
Stack<Node> stack = new Stackk<Node>();
stack.add(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);
}
}
}
System.out,println();
}
中序遍历:先将二叉树的左边界依次入栈,头节点出栈并打印,判断该节点是否有右子树,如果有则再将其子树的左边界入栈,递归实现,若没有右子树,继续将栈顶节点出栈并打印,如果有右子树则再将其子树左边界入栈,递归实现
public static void inOrderUnRecur(Node head){
System.out.println("InOrder:");
if(head != null){
Stack<Node> stack = new Stack<Node>();
while(!stackk.isEmpty() || head != null){
if(head != null){
stack.push(head);
head = head.left;
}else{
head = stack.pop();
System.out.print(head.value + " ");
head = head.right;
}
}
}
System.out.println();
}
后序遍历:头节点入栈,用一个变量表示栈顶
public static void posOrderUnRecur1(Node head){
System.out.print("PosOrder:");
if(head != null){
Stack<Node> s1 = new Stack<Node>();
Stack<Node> s2 = new Stack<Node>();
si.push(head);
while(!s1.isEmpty()){
head = s1.pop();
s2.push(head);
if(head.left != null){
s1.push(head.left);
}
if(head.right != null){
s1.push(head.right);
}
}
while(!s2.isEmpty()){
System.out.print(s2.pop().value + " ");
}
}
System.out,println();
}
public static void posOrderUnRecur2(Node h){
Sytem.out.print("PosOrder:");
if(h != null){
Stack<Node> stack = new Stack<Node>();
stack.push(h);
Node c = null;
while(!stack.isEmpty()){
c = stack.peek();
if(c.left != null && h != c.left && h != c.right){
stack.push(c.left);
}else if(c.right != null && h != c.right){
stack.push(c.right);
}else{
System.out.print(stack.pop().value + " ");
h = c;
}
}
}
System.out.println();
}