110.平衡二叉树 Balanced Binary Tree
综合完之前的两道题目,再写一面受益匪浅.
class Solution{
private:
int height(TreeNode* node){
if (node == NULL){
return 0;
}
int leftheight = height(node->left);
if (leftheight == -1){
return -1;
}
int rightheight = height(node->right);
if (rightheight == -1){
return -1;
}
int result;
if (abs(rightheight - leftheight) > 1){
result = -1;
} else{
result = 1 + max(leftheight, rightheight);
}
return result;
}
public:
bool isBalanced(TreeNode* root) {
if (root == NULL){
return true;
}
return height(root) == -1 ? false : true;
}
};
257. 二叉树的所有路径 Brinary Tree Paths
最基础明白递归和回溯原理的代码
class Solution {
private:
void traversal(TreeNode* node, vector<int>& path, vector<string>& result){
path.push_back(node->val);
if (node->left == NULL && node->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]);
result.push_back(spath);
return;
}
if (node->left){
traversal(node->left, path, result);
path.pop_back();
}
if (node->right){
traversal(node->right, path, result);
path.pop_back();
}
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
vector<int> path;
if (root == NULL){
return result;
}
traversal(root, path, result);
return result;
}
};
精简版:
class Solution {
private:
void traversal(TreeNode* node, string path, vector<string>& result){
path += to_string(node->val);
if (node->left == NULL && node->right == NULL){
result.push_back(path);
return; }
if (node->left){
traversal(node->left, path + "->", result);
}
if (node->right){
traversal(node->right, path + "->", result);
}
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
string path;
if (root == NULL){
return result;
}
traversal(root, path, result);
return result;
}
};
404.左叶子之和 Sum of Left Leaves
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == NULL) return 0;
if (root->left == NULL && root->right == NULL) return 0;
int leftvalue = sumOfLeftLeaves(root->left);
if (root->left != NULL && root->left->left == NULL && root->left->right == NULL){
leftvalue = root->left->val;
}
int rightvalue = sumOfLeftLeaves(root->right);
return leftvalue + rightvalue;
}
};