思路
前序遍历是中左右,每次先处理的是中间节点,那么先将跟节点放入栈中,然后将右孩子加入栈,再加入左孩子。
为什么要先加入右孩子,再加入左孩子呢?
因为这样出栈的时候才是中左右的顺序
解法一

class Solution {public List<Integer> preorderTraversal(TreeNode root) {List<Integer> res = new ArrayList<>();if (root == null) {return res;}Deque<TreeNode> stack = new LinkedList<>();stack.push(root);while (!stack.isEmpty()) {TreeNode temp = stack.pop();res.add(temp.val);if (temp.right != null) {stack.push(temp.right);}if (temp.left != null) {stack.push(temp.left);}}return res;}}
时间复杂度:,其中
n 是二叉树的节点数。每一个节点恰好被遍历一次
空间复杂度:,为迭代过程中显式栈的开销,平均情况下为
,最坏情况下树呈现链状,为
解法二
class Solution {public List<Integer> preorderTraversal(TreeNode root) {List<Integer> res = new ArrayList<Integer>();if (root == null) {return res;}Deque<TreeNode> stack = new LinkedList<TreeNode>();while (!stack.isEmpty() || root != null) {while (root != null) {res.add(root.val);stack.push(root);root = root.left;}root = stack.pop();root = root.right;}return res;}}
