Marval-C 2018-10-22 15:34 采纳率: 16.7%
浏览 643

请教下leetcode 404 求树的所有左叶子的值的和

我的思路就是很简单的,广度遍历,也就是俗话说的一层一层遍历二叉树,碰到有左叶子的就把左叶子的值push_back进vector,感觉一点问题也没有啊。。不知道为什么就是少值,请教下巨巨们 。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    private:
    vector<int> a;
    queue<TreeNode *> b;

public:

    int sumOfLeftLeaves(TreeNode* root) {

        if(!root)
            return 0;

        b.push(root);

        while(!b.empty())
        {
            if(b.front()->right&&b.front()->left)
            {
                a.push_back(b.front()->left->val);
                b.push(b.front()->left);
                b.push(b.front()->right);
                b.pop();
            }
            else if(!b.front()->left&&!b.front()->right)
            {
                b.pop();
            }

            else
            {
                if(b.front()->left)
                {
                    a.push_back(b.front()->left->val);
                    b.push(b.front()->left);
                    b.pop();
                }
                else if(b.front()->right)
                {

                    b.push(b.front()->right);
                    b.pop();
                }
            }

        }

        int sum = 0;

        for(int i = 0;i<a.size();i++)
        {
            sum+=a[i];
        }

        return sum;
    }
};

  • 写回答

2条回答 默认 最新

  • devmiao 2018-10-22 16:32
    关注
    评论

报告相同问题?