经过查询资料,主要有两种风格的iterative solution for binary tree traversal
For example, for the preorder traversal, there are two kinds of iterative solutions. Pay attention to the condition of the while loop:
https://leetcode.com/problems/binary-tree-preorder-traversal/
1.指针遍历同时压栈根节点法 while(root!=null||!s.isEmpty()):
http://blog.youkuaiyun.com/linhuanmars/article/details/21428647
List<Integer> res = new ArrayList<Integer>();
while(root!=null||!s.isEmpty()){
if(root!=null){
res.add(root.val);
s.push(root);
root = root.left;
}
else{
TreeNode n = s.pop();
root = n.right;
}
}
return res;
2. 先压栈子节点后弹栈遍历法while(!s.isEmpty()):
https://algorithm.yuanbin.me/zh-hans/binary_tree/binary_tree_preorder_traversal.html
List<Integer> res = new ArrayList<Integer>();
if(root==null){
return res;
}
LinkedList<TreeNode> s = new LinkedList<TreeNode>();
s.push(root);
while(!s.isEmpty()){
TreeNode n = s.pop();
res.add(n.val);
if(n.right!=null){
s.push(n.right);
}
if(n.left!=null){
s.push(n.left);
}
}
return res;
本来我觉得第二种方法好一些,但后来发现inorder用第二种方法很难做。所以为了统一记忆方便,还是都选用第一种只压栈根节点做法吧!