算法day44 左叶子之和

题目描述
力扣404:左叶子之和

思路:递归
求解左叶子之和,我们可以采用中序的方式进行递归,过程中我们只采集左叶子的值,其它的部分只是访问但不收集,整体代码如下。

void traversal(TreeNode cur,int & res){
if(cur == nullptr) return;
if(cur -> left){
traversal(cur->left,res);
if(!cur->left->left && !cur -> left ->right){
res += cur -> left -> val;
}
}
if(cur -> right){
traversal(cur->right,res);
}
}
int sumOfLeftLeaves(TreeNode
root) {
int res = 0;
traversal(root,res);
return res;
}

时间复杂度:O(n)
空间复杂度:O(h)

END

posted on 2025-06-27 09:33  sakura430  阅读(28)  评论(0)    收藏  举报