二叉树非递归后序遍历的4种优雅解法

方法1:状态机法

状态由两个部分组成

  1. 当前树的根节点root
  2. 辅助Stack的状态

算法就是根据当前的状态,不断跳转到下一个状态,直到root和Stack都为空。Stack里存的是当前树遍历之后再处理的节点,也就是当前树的父亲节点。

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> output = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode pre = null;
        while (root != null || stack.size() > 0) {
            if (root != null) {
                stack.push(root);
                root = root.left;
            }
            else {
                root = stack.pop();
                if (root.right == null || pre == root.right) { // no right tree or has been handled
                    output.add(root.val);
                    pre = root;
                    root = null;
                }
                else { //has right child and has not been handled
                    stack.push(root);
                    root = root.right;
                }
            }
        }
        return output;
    }
}

方法2:Working List法

核心是一个Working list,算法不断从中取一个任务进行处理,过程中会产生新的子任务插入到Working list。任务分为两种:

  1. 复合任务:“后序遍历”以当前节点为根结点的树
  2. 打印任务:直接打印当前节点的value

对于复合任务的处理:

  1. 产生3个新的子任务,左右子树的后续遍历任务和当前节点的打印任务
  2. 新任务插入到队列的顺序很关键,要根据后序遍历的语义要求进行插入。因为这个任务队列是Stack,后处理的任务要先插。
class Solution(object):
    def postorderTraversal(self, root):
        result, stack = [], [(root, 1)]
        if root is None: return result
        while len(stack) > 0:
            node, taskType  = stack.pop()
            if taskType == 1: # 1 for traverse job, 插入三个新任务,注意顺序
                stack.append((node, 0)) # 0 for basic print job
                if node.right is not None: stack.append((node.right, 1))
                if node.left is not None: stack.append((node.left, 1))
            else: result.append(node.val)
        return result

方法3:输出头插法

后序遍历要求根节点最后输出,造成了“先访问到,但是不能输出,只能暂存后续再处理”的处理困境。换个思路,能否访问到就输出?答案是肯定的,只要保证先输出的在输出序列最后,类似链表的头插法,在头部插入,先插入的就在序列最后了。

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        LinkedList<Integer> output = new LinkedList<>();
        if (root == null) {
            return output;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            root = stack.pop();
            output.addFirst(root.val);
            if (root.left != null) {
                stack.push(root.left);
            }
            if (root.right != null) {
                stack.push(root.right);
            }
        }
        return output;
    }
}

方法4: 输出序列逆序法

和方法3原理相同,只是不是通过头插进行逆序,而是先正常输出序列,最后再逆序的方式

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> output = new ArrayList<>();
        if (root == null) {
            return output;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            root = stack.pop();
            output.add(root.val);
            if (root.left != null) {
                stack.push(root.left);
            }
            if (root.right != null) {
                stack.push(root.right);
            }
        }

        Collections.reverse(output);
        return output;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值