将二叉搜索树转换为双向链表

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

伪代码:

TreeNode convert(TreeNode root){
    //指向已经转换好的链表的最后一个节点
    TreeNode lastNodeInList
    convert(root,lastNodeInList)
    //get head
    TreeNode head = lastNodeInList
    while (head!=null && head.left!=null)
        head = head.left
    return head
}

void convert(TreeNode node,TreeNode lastNodeInList){
    if(node==null)
        return
    TreeNode current = node
    if(current.left!=null)
        convert(current.left,lastNodeInList)
    //add current
    current.left = lastNodeInList
    if(lastNodeInList!=null)
        lastNodeInList.right = current
    lastNodeInList = current

    if(current.right!=null)
        convert(current.right,lastNodeInList)
}
    原文作者:labmem
    原文地址: https://www.jianshu.com/p/b270f406f603
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞