[leetcode]Convert Sorted Array to Binary Search Tre
Posted on 2013-12-31 19:58 1957 阅读(187) 评论(0) 编辑 收藏 举报排好序的...
中间是root , root左边是left,root右边是right
递归建树.
/** * 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* createTree(vector<int>&num , int start , int end){ if(end < start) return nullptr; int mid = (start + end) / 2; TreeNode* root = new TreeNode(num[mid]); root -> left = createTree(num , start , mid - 1); root -> right = createTree(num , mid + 1 , end); return root; } TreeNode *sortedArrayToBST(vector<int> &num) { int size = num.size(); if (size == 0) return nullptr; return createTree(num , 0 , size - 1); } };
by 1957
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步