public ListpreorderTraversal(TreeNode root) { System.out.println("前序遍历:"); List list = new ArrayList<>(); if (root != null) { //利用栈结构的特性,模仿递归遍历 Stack stack = new Stack (); //先放入头节点 stack.push(root); //循环的终止条件是栈非空 while (!stack.isEmpty()) { TreeNode cur = stack.pop(); list.add(cur.val); if (cur.right != null) { stack.push(cur.right); } if (cur.left != null) { stack.push(cur.left); } } } return list; }



