二叉树中序遍历


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

一、递归中序遍历

    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