首页 > 其他 > 详细

剑指offer(26)二叉搜索树与双向链表

时间:2018-04-06 10:35:01      阅读:210      评论:0      收藏:0      [点我收藏+]

题目描述

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

 

题目分析

要生成排序的双向列表,那么只能是中序遍历,因为中序遍历才能从小到大,所以需要递归,

  • 先对左子数调整为双向链表,并用变量pLast指向最后一个节点
  • 再将中间节点和pLast连起来
  • 再去调整右子树

 

代码

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function Convert(pRootOfTree)
{
    // write code here
    if(pRootOfTree == null) return null;
    let pLast=null;
    pLast=ConvertNode(pRootOfTree,pLast);
    let pHead=pLast;
    while(pHead&&pHead.left){
        pHead=pHead.left;
    }
    return pHead;
}
function ConvertNode(pNode,pLast){
    if(pNode==null) return;
    if(pNode.left){
        pLast=ConvertNode(pNode.left,pLast);
    }
    pNode.left=pLast;
    if(pLast){
        pLast.right=pNode;
    }
    pLast=pNode;
    if(pNode.right){
        pLast=ConvertNode(pNode.right,pLast);
    }
    return pLast;
}

 

剑指offer(26)二叉搜索树与双向链表

原文:https://www.cnblogs.com/wuguanglin/p/Convert.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!