zoukankan      html  css  js  c++  java
  • 最容易理解的二叉树后续遍历非递归java实现

    后续遍历要保证根结点在左孩子和右孩子访问之后才能访问,因此对于任一结点P,先将其入栈。如果P不存在左孩子和右孩子,则可以直接访问它;或者P存在左孩子或者右孩子,但是其左孩子和右孩子都已被访问过了,则同样可以直接访问该结点。若非上述两种情况,则将P的右孩子和左孩子依次入栈,这样就保证了每次取栈顶元素的时候,左孩子在右孩子前面被访问,左孩子和右孩子都在根结点前面被访问。

    private static void postOrderNonRecursiveEasily(Node root) {
           System.out.println("postOrderNonRecursiveEasiliy :");
           Assert.notNull(root, "root is null");
           Node lastVisitNode = null;
           Stack <Node> stack = new Stack <Node>();
           stack.push(root);
           while (!stack.isEmpty()) {
               root = stack.peek();
               //如果P不存在左孩子和右孩子
               //或者存在左孩子或者右孩子,但是其左孩子和右孩子都已被访问过了
               if ((root.getLeftNode() == null && root.getRightNode() == null) || (
                   lastVisitNode != null && (lastVisitNode == root.getLeftNode()
                       || lastVisitNode == root.getRightNode()))) {
                   System.out.println(root.getValue());
                   lastVisitNode = root;
                   stack.pop();
               } else {
                   if (root.getRightNode() != null) {
                       stack.push(root.getRightNode());
                   }
                   if (root.getLeftNode() != null) {
                       stack.push(root.getLeftNode());
                   }
               }
           }
       }
    
  • 相关阅读:
    Coding 账户与 本地 Git 客户端的配置
    leetcode_sort-list
    leetcode_insertion-sort-list
    leetcode_move-zeroes
    search-insert-position
    leetcode_remove-nth-node-from-end-of-list
    leetcode_queue-reconstruction-by-height
    leetcode_valid-parentheses
    leetcode_swap-nodes-in-pairs
    20201115-东北师范大学-助教-周总结-第9次
  • 原文地址:https://www.cnblogs.com/bendantuohai/p/10353560.html
Copyright © 2011-2022 走看看