leetcode 404. 左叶子之和 [dfs bfs] 简单

题目

leetcode 404. 左叶子之和

思路

叶子结点且是左叶子结点,累加

易错点

需要注意根结点为空的情况

if(root==NULL)return 0; //易错点

题解

dfs

#include <iostream>
using namespace std;
struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
bool isLeafNode(TreeNode* root){
	return !root->left&&!root->right;
}
int sumOfLeftLeaves(TreeNode* root) {
	if(root==NULL)return 0;
	int sum=0;
	if(root->left!=NULL) 
		sum+=isLeafNode(root->left)?root->left->val:sumOfLeftLeaves(root->left);
	if(root->right!=NULL) 
		sum+=isLeafNode(root->right)?0:sumOfLeftLeaves(root->right);
	return sum;
}
int main() {
	TreeNode * root = new TreeNode(3); 
	TreeNode * rootl = new TreeNode(9); 
	TreeNode * rootr = new TreeNode(20); 
	TreeNode * rootrl = new TreeNode(15); 
	TreeNode * rootrr = new TreeNode(7); 
	rootr->left=rootrl;
	rootr->right=rootrr;
	root->left = rootl;
	root->right = rootr;
	int sum = sumOfLeftLeaves(root);
	cout<<sum;
	return 0;
}

bfs

#include <iostream>
#include <queue>
using namespace std;
struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
bool isLeafNode(TreeNode* root) {
	return !root->left&&!root->right;
}
int sumOfLeftLeaves(TreeNode* root) {
	if(root==NULL)return 0; //易错点
	queue<TreeNode *> q;
	q.push(root);
	int sum =0;
	while(!q.empty()) {
		TreeNode * now = q.front();
		q.pop();
		if(now->left) {
			if(isLeafNode(now->left)) {
				sum+=now->left->val;
			}else{
				q.push(now->left);
			}
		}
		if(now->right&&!isLeafNode(now->right)) {
			q.push(now->right);
		}
	}
	return sum;
}
int main() {
	TreeNode * root = new TreeNode(3);
	TreeNode * rootl = new TreeNode(9);
	TreeNode * rootr = new TreeNode(20);
	TreeNode * rootrl = new TreeNode(15);
	TreeNode * rootrr = new TreeNode(7);
	rootr->left=rootrl;
	rootr->right=rootrr;
	root->left = rootl;
	root->right = rootr;
	int sum = sumOfLeftLeaves(root);
	cout<<sum;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值