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

    一、递归后序遍历

        public static void postOrder(TreeNode root) {
            if (root == null) {
                return;
            }
            postOrder(root.getLeft());
            postOrder(root.getRight());
            System.out.println(root.getValue());
        }
    

    二、非递归后序遍历

        public static void postOrderIterative(TreeNode root) {
            if (root == null) {
                return;
            }
            Stack<TreeNode> tempTreeNodeStack = new Stack<>();
            Stack<TreeNode> finalTreeNodeStack = new Stack<>();
            tempTreeNodeStack.push(root);
            while (!tempTreeNodeStack.isEmpty()) {
                TreeNode currentNode = tempTreeNodeStack.pop();
                finalTreeNodeStack.push(currentNode);
                if (currentNode.getLeft() != null) {
                    tempTreeNodeStack.push(currentNode.getLeft());
                }
                if (currentNode.getRight() != null) {
                    tempTreeNodeStack.push(currentNode.getRight());
                }
            }
            while (!finalTreeNodeStack.isEmpty()) {
                System.out.println(finalTreeNodeStack.pop().getValue());
            }
        }
    

    采用了两个stack进行,先按照,根节点、右节点、左节点的顺序放入栈中,让再pop出来,最终便是左节点、右节点,根节点的后序遍历顺序。

    作者:iBrake
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
  • 相关阅读:
    wcf通道Channel
    固定位置右下角
    小闹钟(无样式)
    CSS小注意(初级)
    java少包汇总
    maven的pom.xml配置
    myeclipse 手动安装 lombok
    Could not synchronize database state with session
    (转)myeclipse插件—SVN分支与合并详解【图】
    Nginx的启动、停止与重启
  • 原文地址:https://www.cnblogs.com/Brake/p/15257098.html
Copyright © 2011-2022 走看看