20.4.14 左叶子之和 简单

时间复杂度O(n),空间复杂度O(n)

题目

计算给定二叉树的所有左叶子之和。

示例:

在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24

解题、代码思路

  1. 就是树的先序遍历,找到左结点就加到sum

代码

/**
 * 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 {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if(!root) return 0;
        int sum=0;
        stack<TreeNode*> Tstack;
        Tstack.push(root);
        while(!Tstack.empty()){
            TreeNode* p=Tstack.top();
            Tstack.pop();
            if(p->left&&!p->left->left&&!p->left->right) sum+=p->left->val;
            if(p->right) Tstack.push(p->right);
            if(p->left) Tstack.push(p->left);
        }
        return sum;
    }
};
posted @ 2020-04-14 11:23  肥斯大只仔  阅读(92)  评论(0编辑  收藏  举报