/** * 二叉树节点 */ private static class TreeNode { int data; TreeNode leftchild; TreeNode rightchild; TreeNode(int data) { this.data = data; } }
/** * 二叉树非递归前序遍历 * * @param node 二叉树节点 */ public static void preOrderTraveral(TreeNode node) { Stack<TreeNode> stack = new Stack<>(); while (node != null || !stack.isEmpty()) { //迭代访问节点的左孩子,并入栈 System.out.println(node.data); stack.push(node); //如果节点没有左孩子,则弹出栈顶节点,访问节点右孩子 if (!stack.isEmpty()) { node = stack.pop(); node = node.rightchild; } } }