【leetcode】【easy】404. Sum of Left Leaves

404. Sum of Left Leaves

Find the sum of all left leaves in a given binary tree.

Example:

    3
   / \
  9  20
    /  \
   15   7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

题目链接:https://leetcode-cn.com/problems/sum-of-left-leaves/

思路

DFS的思想。

法一:非递归

与普通树遍历循环条件不同的时,为了判断是左孩子还是右孩子,需要提前判断左孩子是否是叶节点。

/**
 * 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*> s;
        s.push(root);
        while(!s.empty()){
            auto tmp = s.top();
            s.pop();
            if(tmp->left){
                if(!tmp->left->left && !tmp->left->right) sum+=(tmp->left->val);
                else s.push(tmp->left);
            }
            if(tmp->right) s.push(tmp->right);
        }
        return 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;
        if(root->left && !root->left->left && !root->left->right) {
            return root->left->val + sumOfLeftLeaves(root->right);
        }
        else return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
    }
};

法三:递归,传递左子节点标志

除了上面的递归方法,还可以在向下递归的时候,告诉其是否是左孩子。

运行速度会更快。

/**
 * 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 || (!root->left && !root->right)) return 0;
        return fun(root->left, true) + fun(root->right, false);
    }
    int fun(TreeNode* root, bool isLeft){
        if(!root) return 0;
        if(isLeft && !root->left && !root->right) return root->val;
        else return fun(root->left, true) + fun(root->right, false);
    }
};
发布了127 篇原创文章 · 获赞 2 · 访问量 3742

猜你喜欢

转载自blog.csdn.net/lemonade13/article/details/104393100