Sum of Left Leaves
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.
Subscribe to see which companies asked this question
1.非递归的代码
(1)出错的非递归的代码
int sumOfLeftLeaves(TreeNode* root) {
if(root == NULL)
return 0;
queue<TreeNode*> que;
TreeNode* pre = NULL;//就像二叉树的后序的非递归遍历的思想一样,用pre来记录上一次从队列中弹出来的节点
que.push(root);
int sum = 0;
while(!que.empty())
{
TreeNode* temp = que.front();
que.pop();
if(pre != NULL && temp == pre->left && temp->left == NULL && temp->right == NULL)
{
sum+=temp->val;
}
pre = temp;
if(temp->left != NULL)
que.push(temp->left);
if(temp->right != NULL)
que.push(temp->right);
}
return sum;
}
原因分析:对于
就像二叉树的后序的非递归遍历的思想一样,用pre来记录上一次从队列中弹出来的节点,注意注释部分的代码思路不正确,因为以下非递归的代码是采用层次遍历的,那么prev的更新存在问题,prev主要是用来记录遍历到当前节点的父节点,如果在层次遍历中,则有可能错位,故而不正确。诸如上述二叉树中,遍历到节点4时,其实记录的prev是节点3,则存在问题.
(2)纠正错误后的代码
int sumOfLeftLeaves(TreeNode* root) {
if(root == NULL)
return 0;
queue<TreeNode*> que;
que.push(root);
int sum = 0;
while(!que.empty())
{
TreeNode* temp = que.front();
que.pop();
if(temp->left != NULL)
{
que.push(temp->left);
if(temp->left->left == NULL && temp->left->right == NULL)
sum += temp->left->val;
}
if(temp->right != NULL)
que.push(temp->right);
}
return sum;
}
2.递归的代码
(1)错误代码(错误的原因何在???)
int sumOfLeftLeaves(TreeNode* root) {
int sum = 0;
if(root != NULL)
sumOfLeftLeaves(root,sum);
return sum;
}
void sumOfLeftLeaves(TreeNode* root,int &sum)
{
if(root->left != NULL)
{
if(root->left->left == NULL && root->left->right == NULL)
sum += root->left->val;
}
sumOfLeftLeaves(root->left,sum);
sumOfLeftLeaves(root->right,sum);
}
(2)正确的递归代码
int sumOfLeftLeaves(TreeNode* root) {
if (!root) return 0;
if (root->left && !root->left->left && !root->left->right)
return root->left->val + sumOfLeftLeaves(root->right);//到达这一步表明该节点的left子节点是叶子节点,那么返回root->left->val+sumOfLeftLeaves(root->right)(由于该节点的左子结点为叶子节点,故只有右孩子节点所在的子树存在左叶子的情况)
return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
}