144. 二叉樹的前序周遊
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.Stack;
import java.util.ArrayList;
class Solution {
/*
利用棧非遞歸前序周遊二叉樹
和中序周遊唯一不一樣的是list.add(cur.val)的位置不同。
*/
public List<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> list = new ArrayList<>();
TreeNode cur=root;
while(!stack.isEmpty()||cur!=null){
while(cur!=null){
list.add(cur.val);
stack.push(cur);
cur=cur.left;
}
TreeNode tmp = stack.pop();
cur=tmp.right;
}
return list;
}
}