二叉树后序非递归遍历

2018/08/13 Offer 共 893 字,约 3 分钟

title

problem link

Given a binary tree, return the postorder traversal of its nodes’ values.

For example:

Given binary tree{1,#,2,3},

   1
    \
     2
    /
   3

return[3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

二叉树后序非递归遍历

solution

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;
public class Solution {
    public ArrayList<Integer> postorderTraversal(TreeNode root) {
        ArrayDeque<TreeNode> stack=new ArrayDeque<>();
        if(root==null) return new ArrayList<>();
        stack.push(root);
        ArrayList<Integer> res=new ArrayList<>();
        TreeNode pre=null,cur=null;
        while (!stack.isEmpty()){
            cur=stack.peek();
            if(cur.left==null&&cur.right==null||(pre!=null&&(pre==cur.left||pre==cur.right))) {
                res.add(cur.val);
                stack.pop();
                pre=cur;
            }else{
                if(cur.right!=null){
                    stack.push(cur.right);
                }
                if(cur.left!=null){
                    stack.push(cur.left);
                }
            }
        }
        return res;
    }
}

Search

    Table of Contents