(树)根据排序数组或者排序链表重新构建BST树

  • 题目一:给定一个数组,升序数组,将他构建成一个BST
  • 思路:升序数组,这就类似于中序遍历二叉树得出的数组,那么根节点就是在数组中间位置,找到中间位置构建根节点,然后中间位置的左右两侧是根节点的左右子树,递归的对左右子树进行处理,得出一颗BST
  • 代码:
    /**
     * 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 *sortedArrayToBST(vector<int> &num) {
            return sortedArrayToBST(0, num.size()-1, num);
        }
        TreeNode *sortedArrayToBST(int left, int right, vector<int> &num){
            if (left > right)
                return NULL;
            int mid = (left + right)/2 + (left + right)%2 ;
            TreeNode *root = new TreeNode(num[mid]);
            root->left = sortedArrayToBST(left, mid-1, num);
            root->right = sortedArrayToBST(mid+1, right, num);
            return root;
        }
    };
  • 题目二:和第一题类似,只不过数组变成了链表。
  • 代码:
    /**
     * 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) {
            vector<int> num;
            if (head == NULL)
                return NULL;
            while (head){
                num.push_back(head->val);
                head = head->next;
            }
            return sortListToBST(0, num.size()-1, num);
        }
        TreeNode *sortListToBST(int start, int end, vector<int> &num){
            if (start > end)
                return NULL;
            int mid = (end + start)/2 + (end + start)%2;
            TreeNode *root = new TreeNode(num[mid]);
            root->left = sortListToBST(start, mid-1, num);
            root->right = sortListToBST(mid+1, end, num);
            return root;
        }
    };
原文地址:https://www.cnblogs.com/Kobe10/p/6369617.html