二叉树中序遍历

中序遍历:左子树,根节点,右子树。

一、递归中序遍历

    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();
        }
    }

一次性找到最左边的节点。这个节点就可以马上出栈了。出栈后需要再遍历其右子树。。

posted @ 2021-09-11 23:07  xuan_wu  阅读(400)  评论(0编辑  收藏  举报