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.
求左叶子结点的值之和
java(10ms):
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int sumOfLeftLeaves(TreeNode root) { 12 if (root == null) 13 return 0 ; 14 int ans = 0 ; 15 Queue<TreeNode> que = new LinkedList<TreeNode>() ; 16 que.offer(root) ; 17 while(!que.isEmpty()){ 18 TreeNode cur = que.poll() ; 19 if (cur.left != null && cur.left.left==null && cur.left.right == null) 20 ans += cur.left.val ; 21 if (cur.left != null) 22 que.offer(cur.left) ; 23 if (cur.right != null) 24 que.offer(cur.right) ; 25 } 26 return ans ; 27 } 28 }
C++(6ms):
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int sumOfLeftLeaves(TreeNode* root) { 13 if(root == NULL) 14 return 0 ; 15 queue<TreeNode*> q ; 16 q.push(root) ; 17 int sum = 0 ; 18 while(!q.empty()){ 19 TreeNode* t = q.front(); 20 q.pop(); 21 if(t->left != NULL && t->left->left == NULL && t->left->right == NULL) 22 sum += t->left->val ; 23 if(t->left != NULL) 24 q.push(t->left) ; 25 if(t->right != NULL) 26 q.push(t->right) ; 27 28 } 29 return sum ; 30 } 31 };
C++:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int sumOfLeftLeaves(TreeNode* root) { 13 if(root == NULL) 14 return 0 ; 15 queue<TreeNode*> q ; 16 q.push(root) ; 17 int sum = 0 ; 18 while(!q.empty()){ 19 int len = q.size() ; 20 for(int i = 0 ; i < len ; i++){ 21 TreeNode* t = q.front(); 22 q.pop(); 23 if(t->left != NULL && t->left->left == NULL && t->left->right == NULL) 24 sum += t->left->val ; 25 if(t->left != NULL) 26 q.push(t->left) ; 27 if(t->right != NULL) 28 q.push(t->right) ; 29 } 30 } 31 return sum ; 32 } 33 };