404. 左叶子之和
给定二叉树的根节点 root ,返回所有左叶子之和。
class Solution {
private:
void sum_left(TreeNode *cur,vector<TreeNode*> &path,vector<int> &res){
path.push_back(cur);
if(cur->left == nullptr && cur->right == nullptr)
{
int len = path.size();
if(len <= 1) return;
TreeNode *node = path[path.size() - 2];
if(cur == node->left)
res.push_back(cur->val);
return;
}
if(cur->left){
sum_left(cur->left,path,res);
path.pop_back();
}
if (cur->right) {
sum_left(cur->right, path, res);
path.pop_back();
}
}
public:
int sumOfLeftLeaves(TreeNode* root) {
vector<int> result;
vector<TreeNode*> path;
if (root == NULL) return 0;
sum_left(root, path, result);
int sum = 0;
for(const auto &q:result)
{
sum += q;
}
return sum;
}
int sumOfLeftLeaves1(TreeNode* root) {
vector<int> result;
vector<TreeNode*> path;
if (root == NULL) return 0;
sum_left(root, path, result);
int sum = 0;
for(const auto &q:result)
{
sum += q;
}
return sum;
}
int sumOfLeftLeaves2(TreeNode* root) {
stack<TreeNode*> st;
if (root == NULL) return 0;
st.push(root);
int result = 0;
while (!st.empty()) {
TreeNode* node = st.top();
st.pop();
if (node->left != NULL && node->left->left == NULL && node->left->right == NULL) {
result += node->left->val;
}
if (node->right) st.push(node->right);
if (node->left) st.push(node->left);
}
return result;
}
};
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理