零 .平衡二叉树(见DAY10补充,还是有所遗忘)
一.二叉树的所有路径
class Solution {
public:
void construct_paths(TreeNode* root,string path,vector<string>& paths){
//要想到用path存一条路径,用paths存path
if(root!=NULL){
path += to_string(root->val);//string型相加等于直接拼接
if(root->left==NULL&&root->right==NULL){
paths.push_back(path);
}else{
path+="->";
construct_paths(root->left,path,paths);//往左子树拼接
construct_paths(root->right,path,paths);//往右子树拼接
}
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> paths;
construct_paths(root,"",paths);
return paths;
}
};
或者:
class Solution {
public:
void construct_paths(TreeNode* root,string path,vector<string>& paths){
if(root == NULL)return;
path += to_string (root->val);
if(root->left == NULL&&root->right == NULL){
paths.push_back(path);
}else{
path += "->";
construct_paths(root->left,path,paths);
construct_paths(root->right,path,paths);
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> paths;
construct_paths(root,"",paths);
return paths;
}
};
但是当construc_paths的传入参数中的
vector<string>& paths
变为
vector<string> paths
之后,输出的结果一直为空集。
是因为不用引用的话相当于复制一个数组传参的,但是原数组不改变!!!!所以输出的才会一直为空集
二.左叶子之和(需复习)
给定二叉树的根节点 root
,返回所有左叶子之和。
示例 1:
输入: root = [3,9,20,null,null,15,7] 输出: 24 解释: 在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
//做该题时,卡到了如何得到左叶子节点的读数上以及如何累加上。
class Solution {
int res = 0;
public:
//因为要求和,这里存放全局变量存放累加的左叶子节点之和
int sumOfLeftLeaves(TreeNode* root) {
//1.当根节点为空时
if(root == NULL)return 0;
//2.遇到左叶子节点则如下处理
if(root->left != NULL&&root->left->left == NULL&&root->left->right == NULL){
res += root->left->val;//中
}
//在左子树中寻找左叶子节点并处理。
sumOfLeftLeaves(root->left);//左
//在右子树中寻找左叶子节点并处理
sumOfLeftLeaves(root->right);//右
return res;
}
};