将有序数组转换成二叉搜索树
正常递归,中序遍历
递归经常会把自己绕晕,还是得画图分析
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { private: //递归三部曲:确定递归的参数,返回的是依据数组下标从[l,r]构建的二叉树 TreeNode* tree(vector&nums,int l,int r) { //当下标不合适之后结束递归 if(l>r) return NULL; //确定单层递归的逻辑 //中间节点为头结点,左右子树分别为左右数组组成的二叉树 int mid=(r-l)/2+l; TreeNode* root= new TreeNode(nums[mid]); root->left=tree(nums,l,mid-1); root->right=tree(nums,mid+1,r); return root; } public: TreeNode* sortedArrayToBST(vector & nums) { int l=0; int r=nums.size()-1; return tree(nums,l,r); } };
还没有评论,来说两句吧...