码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-06-24 17:21:55      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:双链表   style   链表   pre   双向链表   todo   bsp   solution   while   

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

样例

给定一个二叉查找树:

    4
   /  \
  2   5
 / \
1  3

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

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 * Definition of Doubly-ListNode
 * class DoublyListNode {
 * public:
 *     int val;
 *     DoublyListNode *next, *prev;
 *     DoublyListNode(int val) {
 *         this->val = val;
           this->prev = this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param root: The root of tree
     * @return: the head of doubly list node
     */
     
    DoublyListNode* list = NULL;
    DoublyListNode* bstToDoublyList(TreeNode* root) {
        // Write your code here
        if (root == NULL) return NULL;
        inorder(root);
        while (list->prev != NULL) list = list->prev;
        return list;
    }
    
    void inorder(TreeNode* root) {
        if (root->left != NULL) inorder(root->left);
        DoublyListNode* temp = new DoublyListNode(root->val);
        if (list == NULL) {
            list = temp;
        }
        else if (list != NULL) {
            list->next = temp;
            temp->prev = list;
            list = temp;
        }
        if (root->right != NULL) inorder(root->right);
    }
};

 

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

标签:双链表   style   链表   pre   双向链表   todo   bsp   solution   while   

原文地址:http://www.cnblogs.com/lingd3/p/7073690.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!