二叉树的非递归前序遍历 需要一个栈来作为辅助存储
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<Integer>();
Stack<TreeNode> stk = new Stack<TreeNode>();
if(root!=null){
stk.push(root);
}
while(!stk.isEmpty()){
TreeNode el = stk.pop();
result.add(el.val);
if(el.right!=null){
stk.push(el.right);
}
if(el.left!=null){
stk.push(el.left);
}
}
return result;
}
}
转载于:https://blog.51cto.com/kcy1860/1334472