1、前序遍历
递归:
public class preOrder_recursion { public static void preOrder(BinaryTreeNode root) { if (root == null) { return; } System.out.print(root.val + " "); preOrder(root.left); preOrder(root.right); } }
迭代:
import java.util.Stack; /** * Created by xzy on 2017/4/16. */ public class preOrder_iteration { public static void preOrder(BinaryTreeNode node) { if (node == null) { return; } Stack<BinaryTreeNode> st = new Stack<BinaryTreeNode>(); while (true) { while (node != null) { System.out.print(node.val + " "); st.push(node); node = node.left; } if (st.empty()) { break; } node = st.pop().right; } } }
2、中序遍历:
递归:
public class inOrder_recursion { public static void inOrder(BinaryTreeNode node){ if (node == null) { return; } inOrder(node.left); System.out.print(node.val + " "); inOrder(node.right); } }
迭代:
import java.util.Stack; /** * Created by xzy on 2017/4/16. */ public class inOrder_iteration { public static void inOrder(BinaryTreeNode node) { if (node == null) { return; } Stack<BinaryTreeNode> st = new Stack<BinaryTreeNode>(); while (true) { while (node != null) { st.push(node); node = node.left; } if (st.empty()) { break; } node = st.pop(); System.out.print(node.val + " "); node = node.right; } } }
3、后续遍历:
递归:
package treeOrder; /** * Created by xzy on 2017/4/16. */ public class postOrder_recursion { public static void postOrder(BinaryTreeNode node) { if (node == null) { return; } postOrder(node.left); postOrder(node.right); System.out.print(node.val + " "); } }
迭代:
import java.util.Stack; /** * Created by xzy on 2017/4/16. */ public class postOrder_iteration { public static void postOrder(BinaryTreeNode node) { if (node == null) { return; } Stack<BinaryTreeNode> st = new Stack<BinaryTreeNode>(); while (true) { while (node != null) { st.push(node); node = node.left; } while (!st.empty()) { if (node == st.peek().left && st.peek().right != null) { node = st.peek().right; break; } else { node = st.pop(); System.out.print(node.val + " "); } } if (st.empty()) { break; } } } }
4、层次遍历:
import java.util.LinkedList; /** * Created by xzy on 2017/4/16. */ public class LevelOrder { public static void levelOrder(BinaryTreeNode node) { if (node == null) { return; } LinkedList<BinaryTreeNode> queue = new LinkedList<BinaryTreeNode>(); queue.add(node); while (!queue.isEmpty()) { node = queue.poll(); System.out.print(node.val + " "); if (node.left != null) { queue.add(node.left); } if (node.right != null) { queue.add(node.right); } } } }