二叉树
13. 二叉树的所有路径
思路:
先序遍历获取路径,在叶子节点处将路径转化为字符串结果的格式。
回溯的方式更新答案。
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
vector<int> path;
if (root == NULL) return result;
preorder(root, path, result);
return result;
}
private:
void preorder(TreeNode *root, vector<int> &path, vector<string> &result) {
path.push_back(root->val); // 只有不为空的节点才会被继续递归
if (root->left == NULL && root->right == NULL) {
string sPath = "";
int size = path.size();
for (int i = 0; i < size - 1; i++) {
sPath += to_string(path[i]);
sPath += "->";
}
sPath += to_string(path[size - 1]);
result.push_back(sPath);
}
if (root->left) {
preorder(root->left, path, result);
path.pop_back();
}
if (root->right) {
preorder(root->right, path, result);
path.pop_back();
}
}
};
简化回溯过程, 精简代码
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
string path;
if (root == NULL) return result;
preorder(root, path, result);
return result;
}
private:
void preorder(TreeNode *root,string path, vector<string> &result) {
path += to_string(root->val); // 只有不为空的节点才会被继续递归
if (root->left == NULL && root->right == NULL) {
result.push_back(path);
}
if (root->left) {
preorder(root->left, path + "->", result);
}
if (root->right) {
preorder(root->right, path + "->", result);
}
}
};
15. 左叶子之和
思路: 层序遍历
给每个遍历到的节点打个标记,如果是左节点则记为true
,否则记录为false
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
int sum = 0;
if (root == NULL) return sum;
queue<pair<TreeNode *, bool>> que; // true 代表进入左分支
que.push({root, false});
// cout << "hello" << endl;
while (!que.empty()) {
int size = que.size();
for (int i = 0; i < size; i++) {
pair<TreeNode *, bool> cur = que.front(); que.pop();
if (cur.first->left == NULL && cur.first->right == NULL && cur.second == true) sum += cur.first->val;
if (cur.first->left) que.push({cur.first->left, true});
if (cur.first->right) que.push({cur.first->right, false});
}
}
return sum;
}
};
思路二:
后续遍历,遇到叶子节点返回 0,遇到左叶子节点将返回值修改为左叶子的值(在递归左分支的时候处理)。
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == 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);
return leftValue + rightValue;
}
};