题目:404. 左叶子之和
思路
前序遍历(随便怎么遍历);
在遇到左叶子时处理数据,选择中、左、右
里面的左
的时候再判断这个节点是不是叶子;
代码
/*** 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 result = 0;void travel(TreeNode* cur){if(cur == NULL){return;}// 中// 左if(cur->left){TreeNode* left_temp = cur->left;if(left_temp->left == NULL && left_temp->right == NULL){result += left_temp->val;}travel(cur->left);}// 右if(cur->right){travel(cur->right);}}int sumOfLeftLeaves(TreeNode* root) {if(root == NULL){return 0;}travel(root);return result;}
};