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;
    }
};
posted @   xiazichengxi  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示
主题色彩