describe
Find the sum of the values of all the left leaf nodes of a binary tree.
A binary tree node is defined as follows:
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
The code of the title part has been completed, you only need to add and submit the following functions:
int sumOfLeftLeaves(struct TreeNode* root);
enter
The input is a number of integers (not more than 512) representing the node element value of a binary tree in sequential representation, where 0 indicates that the corresponding node of the binary tree is empty. Input ends with -1.
output
Output the sum of the element values of all left leaf nodes.
sample input
1 2 3 4 5 0 0 0 0 6 7 -1
Sample output
10
#include<bits/stdc++.h> using namespace std; struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; int s; void dfs(TreeNode*root) { if(!root) return; if(root->left) { if(!root->left->left&&!root->left->right) s+=root->left->val; dfs(root->left); } if(root->right) dfs(root->right); } int sumOfLeftLeaves(TreeNode* root) { dfs(root); return s; } TreeNode*creat() { int front=1,rear=0,x; TreeNode*qu[1005],*t,*root=NULL; while(scanf("%d",&x)!=EOF,x!=-1) { if(x==0) t=NULL; else { t=new TreeNode; t->val=x; t->left=NULL; t->right=NULL; } qu[++rear]=t; if(rear==1) root=t; else { if(t&&qu[front]) { if(rear%2==0) qu[front]->left=t; else qu[front]->right=t; } if(rear%2==1) front++; } } return root; } intmain () { TreeNode*x=creat(); printf("%d\n",sumOfLeftLeaves(x)); return 0; }