题目来源:leetcode
刷题顺序:代码随想录
刷题工具:VSCode+leetcode插件
补充:延毕时间充裕,会结合LeetCode 101: A LeetCode Grinding Guide (C++ Version)相似题目一起做。
题目:
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
输入:root = [3,9,20,null,null,15,7]
输出:true
代码:
class Solution {
public:
int getHeight(TreeNode* root){
int depth = 0;
if (root == NULL) return 0;
int leftdepth = getHeight(root->left);
if (leftdepth == -1) return -1;
int rightdepth = getHeight(root->right);
if (rightdepth == -1) return -1;
if (abs(leftdepth-rightdepth) > 1) return -1;
else{
return 1 + max(leftdepth, rightdepth);
}
}
bool isBalanced(TreeNode* root) {
if (root == NULL) return true;
if (getHeight(root) == -1) return false;
else return true;
}
};
这道题竟然是简单题,我无语了,我太笨了吗好烦
题目:
给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
示例:
输入:root = [1,2,3,null,5]
输出:["1->2->5","1->3"]
代码:
class Solution {
public:
void getString(TreeNode* cur, vector<int>& path, vector<string>& res){
path.push_back(cur->val);
if (cur->left == NULL && cur->right == NULL){
string spath;
for (int i = 0; i < path.size()-1; ++i){
spath += to_string(path[i]);
spath += "->";
}
spath += to_string(path[path.size()-1]);
res.push_back(spath);
}
if (cur->left){
getString(cur->left, path, res);
path.pop_back();
}
if (cur->right){
getString(cur->right, path, res);
path.pop_back();
}
return;
}
vector<string> binaryTreePaths(TreeNode* root) {
//这竟然是简单题,难以置信
vector<int> path;
vector<string> res;
if (root == NULL) return res;
getString(root, path, res);
return res;
}
};
题目:
给定二叉树的根节点 root ,返回所有左叶子之和。
输入: root = [3,9,20,null,null,15,7]
输出: 24
解释: 在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
代码:
class Solution {
public:
int sum;
int sumOfLeftLeaves(TreeNode* root) {
if (root == NULL) return 0;
int leftnum = sumOfLeftLeaves(root->left);
if (root->left != NULL && root->left->left == NULL && root->left->right == NULL){
leftnum = root->left->val;
}
int rightnum = sumOfLeftLeaves(root->right);
sum = leftnum + rightnum;
return sum;
}
};
今天感觉没什么心思做。
而且后面两道题竟然都是简单题,通过率这么高,可是我的递归水平像依托答辩。。。
怎么写都递归不出来
哎,好烦好烦