二叉树先序遍历


先序遍历:根节点,左节点,右节点。

一、递归先序遍历

递归方式比较直接明了。

    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