二叉樹先序遍歷


先序遍歷:根節點,左節點,右節點。

一、遞歸先序遍歷

遞歸方式比較直接明了。

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

二、非遞歸先序遍歷

非遞歸采用棧的特性進行。

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


免責聲明!

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



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