二叉樹中序遍歷


中序遍歷:左子樹,根節點,右子樹。

一、遞歸中序遍歷

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

二、非遞歸中序遍歷

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

一次性找到最左邊的節點。這個節點就可以馬上出棧了。出棧后需要再遍歷其右子樹。。


免責聲明!

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



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