链表-109. 有序链表转换高度平衡二叉搜索树

题目:

给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

例如:

给定的有序链表: [-10, -3, 0, 5, 9],

一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:

      0
     / \
   -3   9
   /   /
 -10  5

做法:

与归并排序一样,每次选取中间值作为节点,节点的左子树范围为为坐标0到中间值坐标-1,右子树为中间值坐标+1到末尾,

递归上述过程直至头节点大于尾节点.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int getLength(ListNode* l){
        int cnt=0;
        while(l){
            l=l->next;
            cnt++;
        }
        return cnt;
    }

    TreeNode* Sort(TreeNode* t,int *a,int start,int tail){
            if(start<=tail){
                int mid=(start+tail)/2;
                t=new TreeNode(a[mid]);
                t->left=Sort(t->left,a,start,mid-1);
                t->right=Sort(t->right,a,mid+1,tail);
            }
            return t;
    }

    TreeNode* sortedListToBST(ListNode* head) {
            ListNode* tmp=head;
            int cnt=getLength(tmp),i=0;
             if(!cnt)  return NULL;
            
            int a[cnt];
            while(head){
                a[i++]=head->val;
                head=head->next;
            }
            
            TreeNode* t;
            return Sort(t,a,0,cnt-1);
    }
};

猜你喜欢

转载自blog.csdn.net/qq_39681830/article/details/82019034