● 110.平衡二叉树
● 257. 二叉树的所有路径
● 404.左叶子之和
110. 平衡二叉树
AVL 它来了.... 感觉数据结构对他的印象都停留在理论,code早忘了
思路是求左右子树高度差肯定没问题
可以用 -1 代表不是平衡二叉树
需要返回的是左右子树的高度最大值(处理 中间结点),所以就有了 res 相关的代码
class Solution {
int subTreeHeight(TreeNode* root) {
if(root == nullptr) return 0;
int left = subTreeHeight(root->left);
if(left < 0) return -1;
int right = subTreeHeight(root->right);
if(right < 0) return -1;
int res = 0;
if(abs(left - right) > 1) {
res = -1;
} else {
res = 1 + max(left, right);
}
return res;
}
public:
bool isBalanced(TreeNode* root) {
int h = subTreeHeight(root);
return h < 0 ? false : true;
}
};
257. 二叉树所有路径
这个题一眼回溯...
回溯都懂,差不多套路
回溯的话都是递归完成纵向遍历,循环完成横向遍历,那二叉树简单,每层固定2次,if判断一下就行
但是代码我已经忘却了,直接看了随想录
顺便记录一下 std::to_string()
class Solution {
void DFS(TreeNode* root, vector<int>& path, vector<string>& res) {
path.push_back(root->val);
if(root->left == nullptr && root->right == nullptr) {
string curPath {};
for(int i = 0; i < path.size(); ++i) {
curPath += to_string(path[i]);
if(i < path.size() - 1) curPath += "->";
}
res.push_back(curPath);
}
if(root->left != nullptr) {
DFS(root->left, path, res);
path.pop_back();
}
if(root->right != nullptr) {
DFS(root->right, path, res);
path.pop_back();
}
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<int> path;
vector<string> res;
if(root == nullptr) return {};
DFS(root, path, res);
return res;
}
};
404. 左叶子之和
想清楚边界就行了。
class Solution {
int getLeftSum(TreeNode* root) {
if(root == nullptr) return 0;
int lval = getLeftSum(root->left);
if(root->left != nullptr && root->left->left == nullptr && root->left->right == nullptr) {
lval = root->left->val;
}
int rval = getLeftSum(root->right);
return lval + rval;
}
public:
int sumOfLeftLeaves(TreeNode* root) {
return getLeftSum(root);
}
};