zoukankan      html  css  js  c++  java
  • 《程序员代码面试指南》第二章 链表问题 搜索二叉树转换为双向链表

    样例

    树的中序遍历:1 2 3 4 5 6 7 ,转换后双向链表的遍历:1 2 3 4 5 6 7
    

    java代码

    /**
     * @Description:搜索二叉树转换为双向链表
     * @Author: lizhouwei
     * @CreateDate: 2018/4/7 10:45
     * @Modify by:
     * @ModifyDate:
     */
    public class Chapter2_15 {
        public DoubleNode treeToDubleNode(Tree tree) {
            //用队列存放将树的中序遍历
            Queue<Tree> trees = new LinkedList<Tree>();
            //中序遍历
            recInOrder(tree, trees);
            //构造双向链表
            tree = trees.poll();
            DoubleNode head = new DoubleNode(tree.vlaue);
            DoubleNode pre = head;
            DoubleNode cur = null;
            while (!trees.isEmpty()) {
                tree = trees.poll();
                cur = new DoubleNode(tree.vlaue);
                pre.next = cur;
                cur.pre = pre;
                pre = cur;
            }
            return head;
        }
    
        public void recInOrder(Tree tree, Queue<Tree> trees) {
            if (tree == null) {
                return;
            }
            recInOrder(tree.left, trees);
            trees.offer(tree);
            recInOrder(tree.right, trees);
        }
    
        //打印树
        public void recInOrder(Tree tree) {
            if (tree == null) {
                return;
            }
            recInOrder(tree.left);
            System.out.print(tree.vlaue + " ");
            recInOrder(tree.right);
        }
    
        //测试
        public static void main(String[] args) {
            Chapter2_15 chapter = new Chapter2_15();
            Tree root = new Tree(4);
            root.left = new Tree(2);
            root.right = new Tree(6);
            root.left.left = new Tree(1);
            root.left.right = new Tree(3);
            root.right.left = new Tree(5);
            root.right.right = new Tree(7);
            chapter.recInOrder(root);
            DoubleNode head = chapter.treeToDubleNode(root);
            Link.printDLink(head);
        }
    }
    
    class Tree {
        public int vlaue;
        public Tree left;
        public Tree right;
    
        public Tree(int vlaue) {
            this.vlaue = vlaue;
        }
    
    }
    
  • 相关阅读:
    vnc安装
    centos下安装图形界面
    granfana telegraf influx安装与使用
    jenkins安装与使用
    yum使用手册
    Python模块--并发相关threading、multiprocessing、Queue、gevent
    Python模块--logging
    Python模块--psutil
    python模块--Beautifulsoup
    Python模块--Pexpect
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8732666.html
Copyright © 2011-2022 走看看