110. 平衡二叉树
class Solution {
public:
int maxDepth(TreeNode* root){
if(root==nullptr)
return 0;
int left=maxDepth(root->left);
int right=maxDepth(root->right);
return 1+max(left,right);
}
bool isBalanced(TreeNode* root) {
if(root==nullptr)
return true;
if(isBalanced(root->left)&&isBalanced(root->right)&&abs(maxDepth(root->left)-maxDepth(root->right))<=1)
return true;
return false;
}
};
257. 二叉树的所有路径
class Solution {
public:
vector<vector<int>> results;
vector<int> temp;
vector<string> join(){
vector<string> ans;
for(auto result:results){
string res=to_string(result[0]);
for(int i=1;i<result.size();i++){
res+="->"+to_string(result[i]);
}
ans.push_back(res);
}
return ans;
}
void dfs(TreeNode* root){
if(root==nullptr)
return;
if(root->left==nullptr&&root->right==nullptr){
// vector<int> res(temp.begin(),temp.end());
// res.push_back(root->val);
results.push_back(temp);
results.back().push_back(root->val);
return;
}
temp.push_back(root->val);
dfs(root->left);
dfs(root->right);
temp.pop_back();
}
vector<string> binaryTreePaths(TreeNode* root) {
dfs(root);
return join();
}
};
终止条件里如果对temp进行更新,会导致回溯出问题, 因此额外创建了一个变量res。
404. 左叶子之和
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root==nullptr)
return 0;
int sum=0;
sum+=sumOfLeftLeaves(root->left);
sum+=sumOfLeftLeaves(root->right);
if(root->left&&root->left->left==nullptr&&root->left->right==nullptr)
sum+=root->left->val;
return sum;
}
};
后续遍历的思路,比较绕的一点是左叶子的判定依赖父节点,从root出发,根据root->left->left/right来判断左子树是否是左叶子。
222. 完全二叉树的节点个数
class Solution {
public:
int countNodes(TreeNode* root) {
if(root==nullptr)
return 0;
int cnt=0;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int n=q.size();
for(int i=0;i<n;i++){
auto node=q.front();
q.pop();
if(node->left)
q.push(node->left);
if(node->right)
q.push(node->right);
cnt++;
}
}
return cnt;
}
};