|
| 1 | +/* |
| 2 | +问题描述: |
| 3 | +
|
| 4 | +Find the sum of all left leaves in a given binary tree. |
| 5 | +
|
| 6 | +Example: |
| 7 | +
|
| 8 | + 3 |
| 9 | + / \ |
| 10 | + 9 20 |
| 11 | + / \ |
| 12 | + 15 7 |
| 13 | +
|
| 14 | +There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. |
| 15 | +*/ |
| 16 | + |
| 17 | + |
| 18 | + |
| 19 | +/** |
| 20 | + * Definition for a binary tree node. |
| 21 | + * struct TreeNode { |
| 22 | + * int val; |
| 23 | + * TreeNode *left; |
| 24 | + * TreeNode *right; |
| 25 | + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} |
| 26 | + * }; |
| 27 | + */ |
| 28 | +class Solution { |
| 29 | +public: |
| 30 | + |
| 31 | + //思路一:递归 |
| 32 | + /* |
| 33 | + int sumOfLeftLeaves(TreeNode* root) { |
| 34 | + if (!root || !root->left && !root->right) |
| 35 | + return 0; |
| 36 | + |
| 37 | + int res = 0; |
| 38 | + //分别左右两支开始进行 |
| 39 | + help(root->left, true, res); |
| 40 | + help(root->right, false, res); |
| 41 | + |
| 42 | + return res; |
| 43 | + } |
| 44 | + |
| 45 | + void help(TreeNode* root, bool isLeft, int &res) { |
| 46 | + if (!root) |
| 47 | + return; |
| 48 | + if (!root->left && !root->right && isLeft) //如果是叶子节点并且是左孩子 |
| 49 | + res += root->val; |
| 50 | + help(root->left, true, res); |
| 51 | + help(root->right, false, res); |
| 52 | + } |
| 53 | + */ |
| 54 | + |
| 55 | + //写法二: |
| 56 | + /* |
| 57 | + int sumOfLeftLeaves(TreeNode* root) { |
| 58 | + if (!root) |
| 59 | + return 0; |
| 60 | + |
| 61 | + //如果该节点的左孩子存在,但它是叶子节点。那就加上自己再计算右子树 |
| 62 | + if (root->left && !root->left->left && !root->left->right) |
| 63 | + return root->left->val + sumOfLeftLeaves(root->right); |
| 64 | + |
| 65 | + return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right); |
| 66 | + } |
| 67 | + */ |
| 68 | + |
| 69 | + //思路二:利用层序遍历,逐个相加计算 |
| 70 | + int sumOfLeftLeaves(TreeNode* root) { |
| 71 | + if (!root || !root->left && !root->right) { |
| 72 | + return 0; |
| 73 | + } |
| 74 | + |
| 75 | + int res = 0; |
| 76 | + queue<TreeNode*> q; |
| 77 | + q.push(root); |
| 78 | + while(!q.empty()) { |
| 79 | + TreeNode* node = q.front(); |
| 80 | + q.pop(); |
| 81 | + //如果是左边叶子节点 |
| 82 | + if (node->left && !node->left->left && !node->left->right) |
| 83 | + res += node->left->val; |
| 84 | + if (node->left) |
| 85 | + q.push(node->left); |
| 86 | + if (node->right) |
| 87 | + q.push(node->right); |
| 88 | + } |
| 89 | + |
| 90 | + return res; |
| 91 | + } |
| 92 | + |
| 93 | + |
| 94 | +}; |
0 commit comments