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

    题目描述

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

    例图:

    解法:

    由于是二叉搜索树,因此中序遍历的结果就是排序的。

    中序遍历利用栈来实现。遍历时,前一个结点的 right 指向后一个结点,后一个结点的 left 指向前一个结点。(10连接左子树的最大值,同时连接右子树的最小值。)

    public TreeNode convert(TreeNode root){
           if(root==null){
               return null;
           }
           Stack<TreeNode> stack = new Stack<>();
           TreeNode cur = root;
           TreeNode res = null;
           TreeNode pre = null;
           while(cur != null || !stack.isEmpty()){
               if(cur != null){
                   stack.push(cur);
                   cur = cur.left;
               }else{
                   cur = stack.pop();
                   if(pre == null){
                       pre = cur;
                       res = pre;
                   }else{
                       pre.right = cur;
                       cur.left = pre;
                       pre = cur;
                   }
                   cur = cur.right;
               }
          }
         return res;
    }

    可转换成递归的方式

  • 相关阅读:
    枚举
    枚举
    比特币中的密码学原理
    贪心
    dp
    二分
    mac解决matplotlib中文乱码
    Keras使用多个GPU并行
    pyspark使用-dataframe操作
    箱线图
  • 原文地址:https://www.cnblogs.com/lisen10/p/11218710.html
Copyright © 2011-2022 走看看