LeetCode Sum of Left Leaves

LeetCode 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.

本题要求二叉树中所有左叶子节点之和。简单题,直接递归,递归的时候记录或判断当前节点是父亲节点的左孩子还是右孩子。完整代码如下: [cpp] class Solution { public: int work(TreeNode *cur, TreeNode *par) { if (cur->left == NULL&&cur->right == NULL&&par->left == cur)return cur->val; int ans = 0; if (cur->left)ans += work(cur->left, cur); if (cur->right)ans += work(cur->right, cur); return ans; } int sumOfLeftLeaves(TreeNode* root) { if (root == NULL)return 0; int sum = 0; if (root->left)sum += work(root->left, root); if (root->right)sum += work(root->right, root); return sum; } }; [/cpp] 本代码提交AC,用时6MS。]]>

Leave a Reply

Your email address will not be published. Required fields are marked *