(樹)根據排序陣列或者排序連結串列重新構建BST樹

Kobe10發表於2017-02-06
  • 題目一:給定一個陣列,升序陣列,將他構建成一個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;
        }
    };

     

相關文章