0
点赞
收藏
分享

微信扫一扫

404.左叶子之和

非凡兔 2022-04-14 阅读 33
c++

记录新手小白的做题历程。


题目:给定二叉树的根节点 root ,返回所有左叶子之和。、


思路:感觉可以用层序遍历,记录每一层第一个结点的和就可以。但是思考之后感觉这样不可行,因为第一个结点不一定是左叶子,可能是右叶子,那我是不是可以用两个队列来存储结点,一个用来遍历,一个用来存储叶结点。


感觉我的思想太复杂了,不能说错了,只能说不对。

某位大佬

递归方法:

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if (root == NULL) return 0;//硬性条件,判断是否为空
        int midValue = 0;//用于记录值
        if (root->left != NULL && root->left->left == NULL && root->left->right == NULL) {
            midValue = root->left->val;//需要通过父结点判断是否为左叶子,先是左孩子不为空,然后再判断是否为左叶子
        }
        return midValue + sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
    }
};

非递归:

class Solution {
public:
    int sumOfLeftLeaves(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;
    }
};

还不错,感觉之前刷的题大多相似,已经限制了自己的思路了,来一个不同一点的,判断父结点。

举报

相关推荐

0 条评论