[leetcode] BST与链表的相互转换

1. 链表-->BST (借鉴smile的)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode *sortedListToBST(ListNode *head) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int cnt = 0;
        ListNode* cur = head;
        while (cur)
        {
            cur = cur->next;
            cnt++;
        }
        
        return build(head, 0, cnt - 1);
    }
    
    TreeNode* build(ListNode* &head, int left, int right)
    {
        if (left > right)
            return NULL;
                    
        int mid = left + (right - left) / 2;
        TreeNode* leftChild = build(head, left, mid - 1);                    
        TreeNode* parent = new TreeNode(head->val);
        parent->left = leftChild;
        head = head->next;
        parent->right = build(head, mid + 1, right);
        return parent;
    }
};

这样做的好处是:不需要不断地traverse,以寻找中间点!!!!!


2. BST-->链表

二叉树转换为双向链表的思想: 保存两个关键的指针:pre指针(上一次访问的指针)和T指针;对于每一个节点,执行T->lchild = prepre;pre->rchild = T; 然后执行pre = T;当中序遍历结束时,二叉搜索树也被转化为双链表了。

void BiTreeToLinklist(BiTree &T)  // change tree to linklist
 {
     if(T != NULL) // 双向链表化
     {
         BiTreeToLinklist(T->lchild);
         T->lchild = pre;
         pre->rchild = T;
         pre = T;
         BiTreeToLinklist(T->rchild);
     }
 }


你可能感兴趣的:(LinkList,Tree)