• 题目一:给定一个数组,升序数组,将他构建成一个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(, num.size()-, num);
    }
    TreeNode *sortedArrayToBST(int left, int right, vector<int> &num){
    if (left > right)
    return NULL;
    int mid = (left + right)/ + (left + right)% ;
    TreeNode *root = new TreeNode(num[mid]);
    root->left = sortedArrayToBST(left, mid-, num);
    root->right = sortedArrayToBST(mid+, 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(, num.size()-, num);
    }
    TreeNode *sortListToBST(int start, int end, vector<int> &num){
    if (start > end)
    return NULL;
    int mid = (end + start)/ + (end + start)%;
    TreeNode *root = new TreeNode(num[mid]);
    root->left = sortListToBST(start, mid-, num);
    root->right = sortListToBST(mid+, end, num);
    return root;
    }
    };

最新文章

  1. Android真机调试 Android.Util.AndroidRuntimeException: You cannot combine custom titles with other title features
  2. linux 的终端字体色和背景色的修改方法(二)
  3. 杨辉三角 &amp;&amp; 鸽兔同校
  4. Java 第一天
  5. 基于Socket的UDP发包程序
  6. [Objective-c 基础 - 1.1] OC类
  7. 数据持久层(三)ODB介绍
  8. spring依赖注入源码分析和mongodb自带连接本地mongodb服务逻辑分析
  9. 熟悉java堆内存和栈内存和mysql的insert语句中含有id的处理
  10. java平台的常用资源
  11. hdu4597 Play Game 区间DP
  12. ●BZOJ 2149 拆迁队
  13. DirectX11 With Windows SDK--21 鼠标拾取
  14. 解决Kettle与Kerberos集成问题
  15. (转)Spring Boot (十四): Spring Boot 整合 Shiro-登录认证和权限管理
  16. 课程一(Neural Networks and Deep Learning),第三周(Shallow neural networks)—— 0、学习目标
  17. python字典获取最大值的键的值
  18. struts2设置加载非默认路径的struts.xml文件解决方案
  19. Android客户端面试题集锦
  20. ADO.NET主要组件

热门文章

  1. MySQL中的交并差
  2. split的用法回顾,快忘记了@ →@
  3. 分表分库之二:唯一ID的生成方法
  4. 理解contextmanager
  5. CentOS7 日期时间设置
  6. 执行make出现“Warning: File `xxx.c' has modification time 2.6e+04 s in the future“警告的解决方法
  7. VS配置附加包含目录技巧
  8. Python 正则表达式之选择
  9. NetBeans+Xdebug调试原理
  10. div+css显示两行或三行文字