二叉树非递归后序遍历的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;
    }
}
1. 递归解法: 先构建二叉树,然后对二叉树进行递归遍历,统计叶子节点的个数。 二叉树的先序序列和中序序列可以唯一确定一棵二叉树,因此可以通过这两个序列构建二叉树。具体步骤如下: 1. 在先序序列中找到第一个元素作为根节点。 2. 在中序序列中找到根节点,将中序序列分为左子树和右子树两部分。 3. 根据左子树和右子树的长度,在先序序列中分别确定左子树和右子树的范围。 4. 递归构建左右子树,直到序列为空。 构建完二叉树之后,对二叉树进行递归遍历,统计叶子节点的个数即可。 代码如下: ```python class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def buildTree(preorder, inorder): if not preorder: return None root = TreeNode(preorder[0]) idx = inorder.index(root.val) root.left = buildTree(preorder[1:idx+1], inorder[:idx]) root.right = buildTree(preorder[idx+1:], inorder[idx+1:]) return root def countLeafNode(root): if not root: return 0 if not root.left and not root.right: return 1 return countLeafNode(root.left) + countLeafNode(root.right) preorder = [1, 2, 4, 5, 3, 6, 7] inorder = [4, 2, 5, 1, 6, 3, 7] root = buildTree(preorder, inorder) print(countLeafNode(root)) # 输出 4 ``` 2. 非递归解法: 使用栈来辅助遍历二叉树,统计叶子节点的个数。 具体步骤如下: 1. 初始化栈,将根节点入栈。 2. 如果栈不为空,弹出栈顶元素。 3. 如果弹出的节点是叶子节点,统计叶子节点个数。 4. 如果弹出的节点有右子树,将右子树入栈。 5. 如果弹出的节点有左子树,将左子树入栈。 6. 重复步骤 2-5,直到栈为空。 代码如下: ```python def countLeafNode(root): if not root: return 0 stack = [root] count = 0 while stack: node = stack.pop() if not node.left and not node.right: count += 1 if node.right: stack.append(node.right) if node.left: stack.append(node.left) return count preorder = [1, 2, 4, 5, 3, 6, 7] inorder = [4, 2, 5, 1, 6, 3, 7] root = buildTree(preorder, inorder) print(countLeafNode(root)) # 输出 4 ``` 注意,这里使用的是先序遍历的方式,也可以使用中序遍历或后序遍历的方式,只需要修改入栈的顺序即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值