Lintcode -378. 将二叉查找树转换成双链表

378. 将二叉查找树转换成双链表

将一个二叉查找树按照中序遍历转换成双向链表。

样例

给定一个二叉查找树:

    4
   / \
  2   5
 / \
1   3		

返回 1<->2<->3<->4<->5

源代码如下:

/**
  * Definition of Doubly-ListNode
 * class DoublyListNode {
 * public:
 *     int val;
 *     DoublyListNode *next, *prev;
 *     DoublyListNode(int val) {
 *         this->val = val;
 *         this->prev = this->next = NULL;
 *     }
 * } * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: The root of tree
     * @return: the head of doubly list node
     */
    DoublyListNode * bstToDoublyList(TreeNode * root) {
        // write your code here
        if (root==NULL) return NULL;
        
        DoublyListNode *left = bstToDoublyList(root->left);
        DoublyListNode *right = bstToDoublyList(root->right);
        
        DoublyListNode *lefttail = left;
        
        while (lefttail!=NULL && lefttail->next!=NULL){
            lefttail = lefttail->next;
        }
        DoublyListNode *mid = new DoublyListNode(root->val);
        mid->prev = lefttail;
        if (lefttail!=NULL){
            lefttail->next = mid;
        }
        mid->next = right;
        if (right!=NULL){
            right->prev = mid;
        }
        if (left!=NULL) {
            return left;
        }
        else return mid;
        
        
        
        
    }
};

    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/qq_41410877/article/details/84892841
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞