zoukankan      html  css  js  c++  java
  • (树)根据排序数组或者排序链表重新构建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;
          }
      };
  • 相关阅读:
    Codevs堆练习
    codevs 3110 二叉堆练习3
    浅谈堆
    codevs 2924 数独挑战
    搜索技巧——持续更新
    2144 砝码称重 2
    codevs 2928 你缺什么
    codevs 2594 解药还是毒药
    codevs 2147 数星星
    判断素数
  • 原文地址:https://www.cnblogs.com/Kobe10/p/6369617.html
Copyright © 2011-2022 走看看