不用递归,那就使用栈来遍历即可
import java.util.ArrayList; import java.util.Stack; public class Solution { public ArrayList<Integer> preorderTraversal(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); ArrayList<Integer> list = new ArrayList<Integer>(); if(root != null){ stack.push(root); } while(stack.size() > 0){ if(stack.peek() != null){ list.add(stack.peek().val); stack.push(stack.peek().left); }else{ stack.pop(); if(stack.size() > 0 && stack.peek() != null){ stack.push(stack.pop().right); } } } return list; } } /** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */