404.左叶子之和
题目链接
static const auto io_speed_up =[](){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
return 0;
}();
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(!root)return 0;
TreeNode *left = root -> left;
if(left &&!(left->left)&&!(left->right))return left -> val + sumOfLeftLeaves(root->right) ;
else return sumOfLeftLeaves(root->right) + sumOfLeftLeaves(left);
}
};
405.数字转换为十六进制数
题目链接
static const auto io_speed_up =[](){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
return 0;
}();
class Solution {
public:
string toHex(int num) {
if(!num)return "0";
string ans = "";
unsigned int k = num;
while(k){
int p = k & 15;
if(p<10)ans += to_string(p);
else ans += ('a' + p - 10);
k>>=4;
}
reverse(ans.begin(), ans.end());
return ans;
}
};

本文解析了两道LeetCode上的经典算法题:左叶子之和与数字转换为十六进制数。对于左叶子之和,我们通过递归遍历二叉树找到所有左叶子节点并计算其总和。在数字转换为十六进制数问题中,我们使用位运算将整数转换为其对应的十六进制字符串表示。代码实现简洁高效,适合算法初学者理解与实践。
6万+

被折叠的 条评论
为什么被折叠?



