zoukankan      html  css  js  c++  java
  • 刷题--二叉搜索树与双向链表

    【题目描述】

    基础:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。

    进阶:要求不能创建任何新的节点,只能调整书中节点指针的指向

    【基础】

    解1:先序遍历二叉树,将遍历结果存入一个队列,再建立双向链表。

     1 /**
     2 public class TreeNode {
     3     int val = 0;
     4     TreeNode left = null;
     5     TreeNode right = null;
     6 
     7     public TreeNode(int val) {
     8         this.val = val;
     9 
    10     }
    11 
    12 }
    13 */
    14 import java.util.*;
    15 
    16 public class Solution {
    17     public TreeNode Convert(TreeNode pRootOfTree) {
    18         // 先序遍历O(N), O(N)
    19         if(pRootOfTree == null)
    20             return null;
    21         LinkedList<TreeNode> que = new LinkedList<TreeNode>();
    22         inOrderToQueue(pRootOfTree, que);
    23         TreeNode head = que.poll();
    24         TreeNode cur = head;
    25         while(que.isEmpty() == false){
    26             cur.right = que.poll();
    27             cur.right.left = cur;
    28             cur = cur.right;
    29         }
    30         return head;
    31     }
    32     
    33     public static void inOrderToQueue(TreeNode head, LinkedList<TreeNode> queue){
    34         if(head == null)
    35             return ;
    36         if(head.left != null)
    37             inOrderToQueue(head.left, queue);
    38         queue.offer(head);
    39         if(head.right != null)
    40             inOrderToQueue(head.right, queue);
    41     }
    42 }
    View Code

    【进阶】

  • 相关阅读:
    每天一个Linux命令(3):ls命令
    Linux忘记root密码的解决办法
    每天一个Linux命令(2):shutdown命令
    (8)序列帧动画
    (7)
    (6)Cocos2d-x 3.0坐标系详解
    (5)调度器(scheduler)
    (4)基础概念介绍——导演、场景、层、精灵
    (3)在Windows7上搭建Cocos2d-x
    (2)Mac环境搭建
  • 原文地址:https://www.cnblogs.com/HITSZ/p/7785008.html
Copyright © 2011-2022 走看看