leecode 108
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
int len= nums.size();
return dfs(nums,0,len);
}
TreeNode* dfs(vector<int>&nums,int left,int right)
{
if(left>=right)
{
return NULL;
}
int mid=(right-left)/2+left;
TreeNode *root=new TreeNode(nums[mid]);
root->left=dfs(nums,left,mid);
root->right=dfs(nums,mid+1,right);
return root;
}
};
主要运用分治的思想,运用二分法来将他的左右子树分开。注意这道题的形成的树并不唯一。
110. 平衡二叉树
class Solution {
public:
bool isBalanced(TreeNode* root) {
if((maxdepth(root))>=0)
return true;
else
return false;
}
int maxdepth(TreeNode *root)
{
int i,j;
if(root==NULL)
return 1;
i=maxdepth(root->left);
if(i<0)
return -1;
j=maxdepth(root->right);
if(j<0)
return -1;
if(i-j>1||j-i>1)
{
return -1;
}
return max(i,j)+1;
}
};
这道题和之前的maxdepth是一个思想,但是这道题需要考虑的是左右子树有一个为空的情况,这一点值得注意。
111. 二叉树的最小深度
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==NULL)
return NULL;
if (root->left == NULL && root->right != NULL) {
return 1 + minDepth(root->right);
}
if (root->right == NULL && root->left != NULL) {
return 1 + minDepth(root->left);
}
return min(minDepth(root->left),minDepth(root->right))+1;
}
};
同样要考虑左右子树为空的情况。
112. 路径总和
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(root==NULL)
return false;
if(root->val==sum&&root->left==NULL&&root->right==NULL)
{
return true;
}
return hasPathSum(root->right,sum-root->val)||hasPathSum(root->left,sum-root->val);
}
};
这道题最精髓的一点是在于sum-root->val这一点,这一点能够写进函数的参数当中,会解决很多事情。
118. 杨辉三角
class Solution {
public:
vector<vector<int>> generate(int numRows) {
int i,j;
if(numRows==1)
return {{1}};
vector<vector<int>>ans;
if(numRows==0)
return ans;
ans.push_back({1});
ans.push_back({1,1});
for(i=2;i<numRows;i++)
{
vector<int> r(i+1,1);
for(j=1;j<i;j++)
{
r[j]=ans[i-1][j-1]+ans[i-1][j];
}ans.push_back(r);
}
return ans;
}
};
没啥好说的主要好先将前两个进行初始化,并且注意数组的下标不要越界。
119. 杨辉三角 II
class Solution {
public:
vector<int> getRow(int rowIndex) {
int i,j;
vector<int>res(rowIndex+1,1);
if(rowIndex==0)
return {{1}};
for(int i = 0;i<rowIndex+1;i++)
{
for(int j =i;j>1;j--)
{
res[j-1] = res[j-1] +res[j-2];
}
}
return res;
}
};
本来想用和上一道题一模一样的思路着,但是他让输出的是一行,那么我们只要将res进行初始化为1,然后注意数组下标并且res返回就可以了。