/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if(null == root)
return res;
Stack<TreeNode> s = new Stack<TreeNode>();
while(!s.isEmpty()||root != null){
while(null != root){
res.add(root.val);
s.push(root);
root = root.left;
}
root = s.pop().right;
}
return res;
}
}
树的前序非递归遍历主要思想是:循环(栈不为空或指针为空);循环左节点入栈,处理当前节点;循环结束左节点为空,弹出栈顶元素,指针指向弹出元素的右节点,继续外层循环。