[关闭]
@LIUHUAN 2019-12-29T17:48:19.000000Z 字数 1383 阅读 824

数组和链表关于BST的转换

algorithm


数组转换成BST(二叉搜索树)

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. TreeNode* sortedArrayToBST(vector<int>& nums) {
  13. int n = nums.size();
  14. return func(nums,0,n-1);
  15. }
  16. TreeNode* func(vector<int> &nums,int i ,int j) {
  17. if(i > j )
  18. return nullptr;
  19. if(i == j ) {
  20. return new TreeNode(nums[i]);
  21. }
  22. int mid = (i + j) / 2;
  23. TreeNode *root = new TreeNode(nums[mid]);
  24. root->left = func(nums,i,mid-1);
  25. root->right = func(nums,mid+1,j);
  26. return root;
  27. }
  28. };

链表转换为二叉搜索树

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. /**
  10. * Definition for a binary tree node.
  11. * struct TreeNode {
  12. * int val;
  13. * TreeNode *left;
  14. * TreeNode *right;
  15. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  16. * };
  17. */
  18. class Solution {
  19. public:
  20. TreeNode* sortedListToBST(ListNode* head) {
  21. vector<ListNode*> vec;
  22. while(head) {
  23. vec.push_back(head);
  24. head = head->next;
  25. }
  26. int n = vec.size();
  27. return func(vec,0,n-1);
  28. }
  29. TreeNode* func(vector<ListNode*> &nums,int i ,int j) {
  30. if(i > j )
  31. return nullptr;
  32. if(i == j ) {
  33. return new TreeNode(nums[i]->val);
  34. }
  35. int mid = (i + j) / 2;
  36. TreeNode *root = new TreeNode(nums[mid]->val);
  37. root->left = func(nums,i,mid-1);
  38. root->right = func(nums,mid+1,j);
  39. return root;
  40. }
  41. };
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注