二叉樹后序遍歷


一、遞歸后序遍歷

    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出來,最終便是左節點、右節點,根節點的后序遍歷順序。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM