404 左叶子之和
本文最后更新于:2021年7月22日 晚上
计算给定二叉树的所有左叶子之和。
示例:
| 3 / \ 9 20 / \ 15 7
在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
|
Solution
- 递归法,后序遍历
- 当我们遍历到节点 node 时,如果它的左子节点是一个叶子结点,那么就将它的左子节点的值累加计入答案。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
class Solution { public: int sumOfLeftLeaves(TreeNode* root) { if (root == NULL) return 0;
int leftValue = sumOfLeftLeaves(root->left); int rightValue = sumOfLeftLeaves(root->right); int midValue = 0; if (root->left && !root->left->left && !root->left->right) { midValue = root->left->val; } int sum = midValue + leftValue + rightValue; return sum; } };
|
| class Solution { public: int sumOfLeftLeaves(TreeNode* root) { if(root==nullptr) return 0; int sum = 0; if(root->left && root->left->left==nullptr && root->left->right==nullptr) sum += root->left->val; sum = sum + sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right); return sum; } };
|
- 迭代法,广度优先搜索
- 借助栈和队列都可以,不过遍历的顺序会有不同
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution { public: int sumOfLeftLeaves(TreeNode* root) { if(root==nullptr) return 0; queue<TreeNode *> q; q.push(root); int sum = 0; while(!q.empty()){ TreeNode* cur = q.front(); q.pop(); if(cur->left){ if(isLeafNode(cur->left)) sum += cur->left->val; else q.push(cur->left); } if(cur->right){ q.push(cur->right); } } return sum; } private: bool isLeafNode(TreeNode* node){ return !node->left && !node->right; } };
|