通过查询资料,主要有两种风格的iterative solution for binary tree traversalhtml
For example, for the preorder traversal, there are two kinds of iterative solutions. Pay attention to the condition of the while loop:java
https://leetcode.com/problems/binary-tree-preorder-traversal/oop
http://blog.csdn.net/linhuanmars/article/details/21428647spa
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;
https://algorithm.yuanbin.me/zh-hans/binary_tree/binary_tree_preorder_traversal.html.net
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用第二种方法很难作。因此为了统一记忆方便,仍是都选用第一种只压栈根节点作法吧!指针