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
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
  • 相关阅读:
    hsdis反汇编java源码工具的使用方法
    final添加内存屏障问题
    Spring-AOP
    Spring-IOC
    IO与NIO
    设计模式学习笔记
    Redis学习笔记
    MySQL优化
    STAR法则
    大文件分割之Linux
  • 原文地址:https://www.cnblogs.com/Brake/p/15257070.html
Copyright © 2011-2022 走看看