110.平衡二叉树
原本想法是封装一个函数求出每个节点的高度,再用条件判断符不符合题目要求。但是这样时间复杂度过高O(N^2)。 所以还是递归的同时标记左右子树是否差值大于1,不符合条件就设定为-1直接返回根节点,然后求根节点的高度即得出答案。
class Solution {
public:
int getHeight(TreeNode* root) {
if(!root) return 0;
int leftHeight = getHeight(root->left);
if(leftHeight == -1) return -1;
int rightHeight = getHeight(root->right);
if(rightHeight == -1) return -1;
return abs(leftHeight - rightHeight) > 1? -1 : 1 + max(leftHeight, rightHeight);
}
bool isBalanced(TreeNode* root) {
return getHeight(root) == -1? false : true;
}
};
257. 二叉树的所有路径
前序遍历,遍历到叶子节点再把保存到数组中的节点写成字符串,最后加入到结果中。注意的点:中止条件是最后一个节点而不是空节点,因为只需要处理最后一个节点,不用考虑空结点的情况。
class Solution {
public:
void getPath(TreeNode* node, vector<string> &res, vector<int> &path) {
//保存节点
path.push_back(node->val);
if(!node->left && !node->right){
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);
}
//TODO
if(node->left){
getPath(node->left,res,path);
path.pop_back();
}
if(node->right){
getPath(node->right,res,path);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
vector<int> path;
getPath(root,res,path);
return res;
}
};
404.左叶子之和
先遍历每一个节点,再判断其左节点是否为题目要求的左节点 if(root->left && !root->left->left && !root->left->right),再求和即可。
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
int sum = 0;
std::function<void(TreeNode*, int&)> transverse = [&](TreeNode* root,int &sum){
if(!root) return;
if(root->left && !root->left->left && !root->left->right) sum += root->left->val;
if(root->left) transverse(root->left,sum);
if(root->right) transverse(root->right,sum);
};
transverse(root, sum);
return sum;
}
};
222.完全二叉树的节点个数
使用任意遍历方式,只需保证访问到一个节点,总数+1即可。
class Solution {
public:
int sum = 0;
int countNodes(TreeNode* root) {
if(!root) return 0;
sum++;
if(root->left) {
countNodes(root->left);
}
if(root->right) {
countNodes(root->right);
}
return sum;
}
};