BitTigerio 2017-10-13
public class Node { int value; Node left; Node right; Node(int data){ this.value = data; } }
public void preOrderRecur(Node node){ if (node == null){ return; } System.out.print(node.value+ " "); preOrderRecur(node.left); preOrderRecur(node.right); }
不断重复步骤3,直到stack为空,全部过程结束。
public void preOrderTraverse(Node node) { if (node == null) return; Stack<Node> stack = new Stack<>(); stack.push(node); while (!stack.empty()) { node = stack.pop(); System.out.print(node.value + " "); if (node.right != null) stack.push(node.right); if (node.left != null) stack.push(node.left); } }
public void inOrderRecur(Node node){ if (node == null) return; inOrderRecur(node.left); System.out.print(node.value+" "); inOrderRecur(node.right); }
当stack为空并且cur为空时,整个过程结束。
public void inOrderTraverse(Node node) { if (node == null) return; Stack<Node> stack = new Stack<>(); Node cur = node; while (!stack.empty()||cur !=null) { if (cur != null) { stack.push(cur); cur = cur.left; }else { node = stack.pop(); System.out.print(node.value+" "); cur = node.right; } } }
public void posOrderRecur(Node node) { if (node == null) { return; } posOrderRecur(node.left); posOrderRecur(node.right); System.out.print(node.value+" "); }
从s2中依次弹出节点并打印,打印的顺序就是后序遍历的顺序了。
public void posOrderTraverse(Node node) { if (node == null) { return; } Stack<Node> s1 = new Stack<>(); Stack<Node> s2 = new Stack<>(); Node cur; s1.push(node); while (!s1.empty()) { cur = s1.pop(); s2.push(cur); if (cur.left != null) s1.push(cur.left); if (cur.right != null) s1.push(cur.right); } while (!s2.empty()) { System.out.print(s2.pop().value+" "); } }
每次令c等于当前stack的栈顶节点,但是不从stack中弹出节点,此时分为一下三种情况。
如果情况1和情况2都不成立,那么从stack中弹出c并打印,然后令h等于c。
public void posOrderTraverse(Node node) { if (node == null) { return; } Stack<Node> stack = new Stack<>(); Node h = node; Node c = null; stack.push(node); while (!stack.empty()) { 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 { c = stack.pop(); System.out.print(c.value + " "); h = c; } } }