- 110.平衡二叉树
- 递归体内两个if用来判断是不是左或右子树已经不平衡,若不平衡就将-1层层返回
- 学习思路和写法
class Solution {
public:
int postOrderSearch(TreeNode* p) {
if (p == nullptr) return 0;
int leftHeight = postOrderSearch(p -> left);
if (leftHeight == -1) return -1;
int rightHeight = postOrderSearch(p -> right);
if (rightHeight == -1) return -1;
return abs(leftHeight - rightHeight) > 1 ? -1 : 1 + max(leftHeight, rightHeight);
}
bool isBalanced(TreeNode* root) {
int res = postOrderSearch(root);
return res == -1 ? false : true;
}
};
- 257.二叉树的所有路径之和
- 初次体会回溯思想,需要多多回顾 | 回溯和递归是绑定的,所以要递归一次,pop一次(暂时不是很理解)
- 精简版本下,path为string,且进行的是值传递不是引用传递,其中回溯的思想进行了隐蔽处理,第一种更好地去体会回溯思想
- 其中写法一,vector< int >path为什么用int,都需要认真思考
class Solution {
public:
void findAllPath(TreeNode* p, vector<int>& path, vector<string> &res) {
path.push_back(p ->val);
if (p -> left == nullptr && p -> right == nullptr) {
string str;
for (int i = 0; i < path.size() - 1; i++) {
str += to_string(path[i]);
str += "->";
}
str += to_string(path[path.size() - 1]);
res.push_back(str);
return;
}
if (p -> left) {
findAllPath(p -> left, path, res);
path.pop_back();
}
if (p -> right) {
findAllPath(p -> right, path, res);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
vector<int> path;
if (root == nullptr) return res;
findAllPath(root, path, res);
return res;
}
};
class Solution {
private:
void traversal(TreeNode* cur, string path, vector<string>& result) {
path += to_string(cur->val);
if (cur->left == NULL && cur->right == NULL) {
result.push_back(path);
return;
}
if (cur->left) traversal(cur->left, path + "->", result);
if (cur->right) traversal(cur->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引用传递,且使用先序遍历,对本人来讲更好理解
- 第二块为随想录代码,使用后序遍历
class Solution {
public:
void findLeftSum(TreeNode* p, int& sum) {
if (p == nullptr) return;
if (p -> left != nullptr && p -> left -> left == nullptr && p -> left -> right == nullptr) {
sum += p -> left -> val;
}
findLeftSum(p -> left, sum);
findLeftSum(p -> right,sum);
}
int sumOfLeftLeaves(TreeNode* root) {
int sum = 0;
findLeftSum(root, sum);
return sum;
}
};
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 && !root->left->left && !root->left->right) {
leftValue = root->left->val;
}
int rightValue = sumOfLeftLeaves(root->right);
int sum = leftValue + rightValue;
return sum;
}
};