【数据结构与算法】左叶子之和

左叶子之和

递归三部曲

  • 确定递归函数的参数和返回值
int sumOfLeftLeaves(TreeNode* root)
  • 确定终止条件
    遍历遇到空节点
if (root == NULL) return 0;
  • 单层的递归逻辑
    遍历顺序:左右中(后序遍历)
    选择后序遍历的原因:要通过递归函数的返回值,累加求左叶子的数值和

错解

//单层递归的逻辑
        int leftValue = sumOfLeftLeaves(root->left);
        if(root->left && !root->left->left && !root->left->right)
        {
            leftValue = root->left->val;
        }
        int rightValue = sumOfLeftLeaves(root->right);
        if(root->right && !root->right->left && !root->right->right)
        {
            rightValue = root->right->val;
        }

        int sum = rightValue + leftValue;
        return sum;

【数据结构与算法】左叶子之和_第1张图片错误原因:这里将右叶子结点也算进去了

正解

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        //递归的终止条件
        if(root == NULL) return 0;
        if(root->left == NULL && root->right == NULL) return 0;
        //单层递归的逻辑
        int leftValue = sumOfLeftLeaves(root->left);
        if(root->left && !root->left->left && !root->left->right)
        {
            leftValue = root->left->val;
        }
        int rightValue = sumOfLeftLeaves(root->right);
       /** if(root->right && !root->right->left && !root->right->right)
        {
            rightValue = root->right->val;
        }**/

        int sum = rightValue + leftValue;
        return sum;

    }
};

你可能感兴趣的:(数据结构与算法,leetcode,算法)