zoukankan      html  css  js  c++  java
  • 三种遍历的非递归实现

        // 非递归前序遍历
        public void preOrderTraversal() {
            preOrder1(root);
        }
    
        private void preOrderTraversal(Node x) {
            LinkedList<Node> list = new LinkedList<>();
            while (x != null || !list.isEmpty()) {
                while (x != null) {
                    System.out.print("[" + x.key + ":" + x.value + "]" + " ");
                    list.addFirst(x);
                    x = x.lchild;
                }
                if (!list.isEmpty()) {
                    x = list.removeFirst();
                    x = x.rchild;
                }
            }
        }
    
        // 中序遍历:左子树--根节点--右子树
        public void inorderTraversal() {
            inorderTraversal(root);
        }
        private void inorderTraversal(Node x) {
            LinkedList<Node> stack = new LinkedList<>();
            while (x != null || !stack.isEmpty()) {
                while (x != null) {
                    stack.addFirst(x);
                    x = x.lchild;
                }
                Node node = stack.removeFirst();
                System.out.print("[" + node.key + ":" + node.value + "]" + " ");
                x = node.rchild;
            }
        }
    
        // 后续遍历思想: 左-右-根;可以视为, 根-右-左,然后结果转置即可.
        public void postOrderTraversal() {
            postOrderTraversal(root);
        }
        private void postOrderTraversal(Node x) {
            LinkedList<Node> stack = new LinkedList<>();
            LinkedList<Node> list = new LinkedList<>();
            stack.addFirst(x);
            while (!stack.isEmpty()) {
                Node node = stack.removeFirst();
                list.add(node);
                if (node.lchild != null)
                    stack.push(node.lchild);
                if (node.rchild != null)
                    stack.push(node.rchild);
            }
            Collections.reverse(list);
            for (Node node : list) {
                System.out.print("[" + node.key + ":" + node.value + "]" + " ");
            }
        }

    借鉴文章:https://my.oschina.net/husthang/blog/852982

  • 相关阅读:
    如何实现进程间的通信
    调试手记
    WinCE的一些忠告——UNICODE编码
    一道字符串复制的面试题目
    strcpy和strncpy区别
    关于#include头文件问题
    rs232串口通讯中,读串口与读端口的区别
    IP包过滤(转)
    小数点后截位问题
    一些函数
  • 原文地址:https://www.cnblogs.com/dongtian-blogs/p/10779562.html
Copyright © 2011-2022 走看看