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;
        }
    
    }
    
  • 相关阅读:
    Ubuntu加上一个命令搜索路径/etc/ environment
    在Ubuntu中编译QT工程Tesful
    Java中的多线程
    [转载]iOS开发之手势识别
    OracleDBA之表管理
    JDBC与JAVA数据库编程
    Oracle之PL/SQL学习笔记
    在Objective-C中浅谈面向对象
    Web前端上万字的知识总结
    类比Spring框架来实现OC中的依赖注入
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8732666.html
Copyright © 2011-2022 走看看