先序遍历:根节点,左节点,右节点。
递归方式比较直接明了。
public static void preOrder(TreeNode root) { if (root == null) { return; } System.out.println(root.getValue()); preOrder(root.getLeft()); preOrder(root.getRight()); }
非递归采用栈的特性进行。
public static void preOrderIterative(TreeNode root) { if (root == null) { return; } Stack<TreeNode> treeNodeStack = new Stack<>(); treeNodeStack.add(root); while (!treeNodeStack.isEmpty()) { TreeNode currentNode = treeNodeStack.pop(); System.out.println(currentNode.getValue()); if (currentNode.getRight() != null) { treeNodeStack.push(currentNode.getRight()); } if (currentNode.getLeft() != null) { treeNodeStack.push(currentNode.getLeft()); } } }