LeetCode404.左叶子之和

题目

法一、广度优先搜索

 1 class Solution {
 2 public:
 3     int sumOfLeftLeaves(TreeNode* root) {
 4         if(root == NULL) return 0;
 5         if(root->left == NULL && root->right == NULL) return 0;
 6         int sum = 0;
 7         queue<TreeNode*>que;
 8         que.push(root);
 9         while(!que.empty()){
10             TreeNode* node = que.front();que.pop();
11             if(node->left != NULL) {
12                 que.push(node->left);
13                 if(node->left->left == NULL && node->left->right == NULL) 
14                     sum += node->left->val;
15             }
16             if(node->right != NULL) {
17                 que.push(node->right);
18             }
19         }
20         return sum;
21     }
22 };

法二、深搜

左叶子之和 = 左子树的左叶子 + 右子树的左叶子

 1 class Solution {
 2 public:
 3      bool isLeafNode(TreeNode *root){
 4         return (!root->left && !root->right);
 5      }
 6         
 7      int dfs(TreeNode* root){
 8         int sum = 0;
 9         if(root->left != NULL){
10             if(root->left != NULL && isLeafNode(root->left)) 
11                 sum += root->left->val;
12             if(!isLeafNode(root->left))   
13                 sum += dfs(root->left);
14         }
15         if(root->right != NULL && !isLeafNode(root->right))
16             sum += dfs(root->right);
17         return sum;
18     }
19 
20     int sumOfLeftLeaves(TreeNode* root) {
21         if(root == NULL) return 0;
22         return dfs(root);
23     }
24    
25     
26 };

注意 sum = 0 一定要放在 dfs内部不能作为全局变量,否则将重复加值

另外一种写法

 1 class Solution {
 2 public: 
 3     bool isLeaf(TreeNode* root){
 4         if(root!=NULL && !root->left && !root->right) return true;
 5         else return false;
 6     }
 7     int sumOfLeftLeaves(TreeNode* root) {
 8         if(root == NULL) return 0;
 9         if(isLeaf(root->left)) return root->left->val + sumOfLeftLeaves(root->right);
10         else return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
11     }
12 };

 

posted @ 2021-01-05 15:58  Uitachi  阅读(32)  评论(0编辑  收藏  举报