publicList<Integer>preorderTraversal(TreeNode root){List<Integer> list =newArrayList<>();Deque<TreeNode> stack =newLinkedList<>();TreeNode t = root;while(!stack.isEmpty()|| t !=null){if(t !=null){
list.add(t.val);
stack.push(t);
t = t.left;}else{// t已经被遍历过,再拿出来的时候需要遍历t的右子树
t = stack.pop();
t = t.right;}}return list;}
迭代(先放右子树,再放左子树)
publicList<Integer>preorderTraversal(TreeNode root){List<Integer> list =newArrayList<>();Deque<TreeNode> stack =newLinkedList<>();if(root==null)return list;TreeNode t = root;
stack.push(t);while(!stack.isEmpty()){
t = stack.pop();
list.add(t.val);if(t.right !=null){
stack.push(t.right);}if(t.left !=null){
stack.push(t.left);}}return list;}