其他分享
首页 > 其他分享> > 二叉树后序遍历

二叉树后序遍历

作者:互联网

一、递归后序遍历

    public static void postOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        postOrder(root.getLeft());
        postOrder(root.getRight());
        System.out.println(root.getValue());
    }

二、非递归后序遍历

    public static void postOrderIterative(TreeNode root) {
        if (root == null) {
            return;
        }
        Stack<TreeNode> tempTreeNodeStack = new Stack<>();
        Stack<TreeNode> finalTreeNodeStack = new Stack<>();
        tempTreeNodeStack.push(root);
        while (!tempTreeNodeStack.isEmpty()) {
            TreeNode currentNode = tempTreeNodeStack.pop();
            finalTreeNodeStack.push(currentNode);
            if (currentNode.getLeft() != null) {
                tempTreeNodeStack.push(currentNode.getLeft());
            }
            if (currentNode.getRight() != null) {
                tempTreeNodeStack.push(currentNode.getRight());
            }
        }
        while (!finalTreeNodeStack.isEmpty()) {
            System.out.println(finalTreeNodeStack.pop().getValue());
        }
    }

采用了两个stack进行,先按照,根节点、右节点、左节点的顺序放入栈中,让再pop出来,最终便是左节点、右节点,根节点的后序遍历顺序。

标签:tempTreeNodeStack,currentNode,后序,遍历,二叉树,null,root,节点,finalTreeNodeStack
来源: https://www.cnblogs.com/Brake/p/15257098.html