public List<Integer> preorderTraversal(TreeNode root) { List<Integer> list = new LinkedList<>(); if (root == null) return list; Stack<TreeNode> stack = new Stack<>(); stack.push(root); while (!stack.isEmpty() { root = stack.pop(); list.add(root.val); if (root.right != null) { stack.push(root.right); } if (root.left != null) { stack.push(root.left); } } return list; } 节点为空返回为空。栈存入根节点,栈不能为空。弹出根节点,集合存放。栈先进后出,先右后左。