思路如下,使用栈,每次把当前节点入栈,然后右子节点入栈,左子节点入栈。
代码如下:
import java.util.*; public class Solution { ArrayList<Integer> list = new ArrayList<Integer>(); public ArrayList<Integer> preorderTraversal(TreeNode root) { if(root == null) return list; Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); while(!stack.isEmpty()){ TreeNode temp = stack.pop(); list.add(temp.val); if(temp.right != null) stack.push(temp.right); if(temp.left != null) stack.push(temp.left); } return list; } }