For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].
分析:此题考查二叉树的前序遍历,此处使用非递归遍历方式实现
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
TreeNode p = root;
//双端队列,实现栈的功能
Deque<TreeNode> stack = new ArrayDeque<>();
while(p!=null || !stack.isEmpty()){
while(p!= null){
list.add(p.val);
stack.push(p);
p = p.left;
}
if(!stack.isEmpty()){
p = stack.pop();
p = p.right;
}
}
return list;
}
}