110.平衡二叉树
题目:110. 平衡二叉树
class Solution {
public:
int height(TreeNode* root){
if(root == nullptr) return 0;
int left_h = height(root->left);
int right_h = height(root->right);
return max(left_h,right_h) + 1;
}
bool isBalanced(TreeNode* root) {
if(root == nullptr) return true;
if(abs(height(root->left) - height(root->right) ) > 1) return false;
return isBalanced(root->left) && isBalanced(root->right);
}
};
257.二叉树的所有路径
class Solution {
public:
vector<string> result;
void dfs(TreeNode *root,vector<int>& path){
path.push_back(root->val);
if(root->left == nullptr && root->right == nullptr){
string temp = "";
for(int i =0 ; i < path.size() - 1; ++i){
temp += to_string(path[i]);
temp += "->";
}
temp += to_string(path[path.size() - 1]);
result.push_back(temp);
return;
}
if(root->left){
dfs(root->left,path);
path.pop_back();
}
if(root->right){
dfs(root->right,path);
path.pop_back();
}
return;
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<int> path;
dfs(root,path);
return result;
}
};
404.左叶子之和
题目:404. 左叶子之和
class Solution {
public:
int ans = 0;
int sumOfLeftLeaves(TreeNode* root) {
if(root == nullptr) return ans;
if(root->left != nullptr && root->left->left == nullptr && root->left->right == nullptr){
ans += root->left->val;
}
if(root->left) sumOfLeftLeaves(root->left);
if(root->right) sumOfLeftLeaves(root->right);
return ans;
}
};
总结
题型:二叉树的迭代,涉及到回溯
技巧:迭代和回溯结合,确定好题目的定义