// 使用额外的容器存储左叶子 -- MYSOLUTION
void get_left_leves_num(TreeNode * root, std::vector<char> &V) // V一定要为&类型,否则会按值传递
{
if (root == nullptr)
{
return;
}
if (root->left == nullptr && root->right == nullptr)
{
return;
}
if (root->left)
get_left_leves_num(root->left, V);
if (root->right)
get_left_leves_num(root->right, V);
if (root->left != nullptr && root->left->left == nullptr && root->left->right == nullptr)
{
V.push_back(root->left->data);
}
}
// 不使用额外容器,返回值类型依据树节点中数据域的类型----KEYS
int traversal(TreeNode * root){
if (root == nullptr) {
return 0;
}
if (root->left == nullptr && root->right == nullptr)
{
return 0;
}
int leftnum = traversal(root->left);
int rightnum = traversal(root->right);
if (root->left != nullptr && root->left->left == nullptr && root->left->right == nullptr)
{
leftnum = root->left->data;
}
return leftnum + rightnum;
}
C++ 代码实现 求二叉树左叶子节点之和
最新推荐文章于 2023-10-08 21:19:23 发布