zoukankan      html  css  js  c++  java
  • 二叉树中序遍历

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

    一、递归中序遍历

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

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

    作者:iBrake
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
  • 相关阅读:
    C
    O
    扩展KMP
    扩欧与乘法逆元
    E
    D
    [LeetCode] Same Tree 深度搜索
    [LeetCode] Remove Duplicates from Sorted List 链表
    [LeetCode] Balanced Binary Tree 深度搜索
    [LeetCode] Remove Nth Node From End of List 快慢指针
  • 原文地址:https://www.cnblogs.com/Brake/p/15257070.html
Copyright © 2011-2022 走看看