zoukankan      html  css  js  c++  java
  • 剑指Offer——二叉搜索树与双向链表

    1、题目描述

      输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

    2、代码实现

    package com.baozi.offer;
    
    /**
     * 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
     *
     * @author BaoZi
     * @create 2019-07-13-9:01
     */
    public class Offer22 {
        public TreeNode Convert(TreeNode pRootOfTree) {
            if (pRootOfTree == null) {
                return null;
            }
            if (pRootOfTree.left == null && pRootOfTree.right == null) {
                return pRootOfTree;
            }
            // 1.将左子树构造成双链表,并返回链表头节点
            TreeNode left = Convert(pRootOfTree.left);
            TreeNode temp_left = left;
            // 2.定位至左子树双链表最后一个节点
            while (temp_left != null && temp_left.right != null) {
                temp_left = temp_left.right;
            }
            // 3.如果左子树链表不为空的话,将当前root追加到左子树链表
            if (left != null) {
                temp_left.right = pRootOfTree;
                pRootOfTree.left = temp_left;
            }
            // 4.将右子树构造成双链表,并返回链表头节点
            TreeNode right = Convert(pRootOfTree.right);
            // 5.如果右子树链表不为空的话,将该链表追加到root节点之后
            if (right != null) {
                right.left = pRootOfTree;
                pRootOfTree.right = right;
            }
            return left != null ? left : pRootOfTree;
        }
    }
    

      

  • 相关阅读:
    洛谷-P1591 阶乘数码
    洛谷-P1328 生活大爆炸版石头剪刀布
    git的使用
    docker下载命令
    springboot学习笔记
    内部类被实例化才会被加载进内存测试
    springboot环境搭建遇到的问题
    Java多线程的锁机制
    spring JdbcTemplate学习
    多线程循环注意
  • 原文地址:https://www.cnblogs.com/BaoZiY/p/11179389.html
Copyright © 2011-2022 走看看