二叉树先序遍历

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

一、递归先序遍历

递归方式比较直接明了。

    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());
            }
        }
    }
posted @ 2021-09-11 22:45  xuan_wu  阅读(383)  评论(0编辑  收藏  举报