思路:
- 遍历二叉树使用递归的方式是比较简单、清晰的,但是这种方法会导致性能的下降,这是因为每次在调用函数时需要为当前函数保存现场,为新调用的函数申请空间,同时如果我们忘记设置递归结束条件还会引起内存栈的溢出。
- 这里讲述的方法是使用迭代的方法实现递归的工作流程。
- 首先递归的本质实际上是压栈,即在又一次调用自身之前,向栈中压入当前函数的状态。
- 我们可以建立辅助栈模拟压栈,对于二叉树的遍历顺序而言,我们要考虑结点入栈的顺序,因为栈先进后出的工作特点,所以向栈中压入结点的顺序直接影响到了我们的访问顺序。
- 而且注意到,递归遍历二叉树时,我们如果要操作某个结点,那么这个结点一定是从递归栈中弹出来的。类比一下,我们在迭代算法中,对第一次弹出的结点按照要求的遍历顺序压入左、右、根三个结点,对第二次弹出的结点进行操作,由此我们可以考虑在辅助栈中压入一个访问标识,这里的代码中用null来标识当前结点已被弹出过栈一次,再次访问时可直接操作。
后序遍历
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
//存储遍历序列
ArrayList<Integer> list=new ArrayList<>();
if(root==null) return list;
//辅助栈
Stack<TreeNode> helper=new Stack<TreeNode>();
//压入根节点
helper.push(root);
while(!helper.isEmpty()){
TreeNode t=helper.pop();
//为第一次弹出,则按照遍历顺序相反的顺序压入根、左、右结点
if(t!=null){
helper.push(t);
//标识t结点已经弹出过一次
helper.push(null);
//压入右结点
if(t.right!=null) helper.push(t.right);
//压入左结点
if(t.left!=null) helper.push(t.left);
}else{
//如果当前结点为标识符null,意味着null结点的下一个结点第二次出栈,可进行额外操作
list.add(helper.pop().val);
}
}
return list;
}
}
前序遍历
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
//存储遍历序列
ArrayList<Integer> list=new ArrayList<>();
if(root==null) return list;
//辅助栈
Stack<TreeNode> helper=new Stack<TreeNode>();
//压入根节点
helper.push(root);
while(!helper.isEmpty()){
TreeNode t=helper.pop();
//为第一次弹出,则按照遍历顺序相反的顺序压入根、左、右结点
if(t!=null){
//压入右结点
if(t.right!=null) helper.push(t.right);
//压入左结点
if(t.left!=null) helper.push(t.left);
helper.push(t);
//标识t结点已经弹出过一次
helper.push(null);
}else{
//如果当前结点为标识符null,意味着null结点的下一个结点第二次出栈,可进行额外操作
list.add(helper.pop().val);
}
}
return list;
}
}
中序遍历
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
//存储遍历序列
ArrayList<Integer> list=new ArrayList<>();
if(root==null) return list;
//辅助栈
Stack<TreeNode> helper=new Stack<TreeNode>();
//压入根节点
helper.push(root);
while(!helper.isEmpty()){
TreeNode t=helper.pop();
//为第一次弹出,则按照遍历顺序相反的顺序压入根、左、右结点
if(t!=null){
//压入右结点
if(t.right!=null) helper.push(t.right);
helper.push(t);
//标识t结点已经弹出过一次
helper.push(null);
//压入左结点
if(t.left!=null) helper.push(t.left);
}else{
//如果当前结点为标识符null,意味着null结点的下一个结点第二次出栈,可进行额外操作
list.add(helper.pop().val);
}
}
return list;
}
}