计算给定二叉树的所有左叶子之和。
示例:
3
/
9 20
/
15 7
在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-of-left-leaves
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法:
递归解法:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int sumOfLeftLeaves(struct TreeNode* root){
if (root == NULL) {
return 0;
}
if (root -> left != NULL && ((root -> left) -> left == NULL) && ((root -> left) -> right == NULL)) {
return (root -> left) -> val + sumOfLeftLeaves(root -> right);
}
return sumOfLeftLeaves(root -> left) + sumOfLeftLeaves(root -> right);
}
非递归解法:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int sumOfLeftLeaves(struct TreeNode* root) {
struct TreeNode *stk[2000];
int stk_index = 0;
struct TreeNode *node = root;
int sum = 0;
while ((stk_index > 0) || (node != NULL)) {
while (node != NULL) {
stk[stk_index++] = node;
node = node -> left;
}
node = stk[--stk_index];
if (node -> left != NULL && ((node -> left) -> left == NULL) && ((node -> left) -> right == NULL)) {
sum += (node -> left) -> val;
}
node = node -> right;
}
return sum;
}