代码随想录刷题——二叉树篇(十)

404. 左叶子之和
递归法:

cpp 复制代码
class Solution{
public:
	int sumOfLeftLeaves(TreeNode* root){
		if(!root) return 0;
		if(!root->left&&!root->right) return 0;
		TreeNode* lf = root->left;
		TreeNode* rt = root->right;
		int lv = sumOfLeftLeaves(lf);
		if(lf&&!lf->left&&!lf->right){
			lv = lf->val;
		}
		int rv = sumOfLeftLeaves(rt);
		return lv+rv;
	}
};

迭代法:

cpp 复制代码
class Solution{
public:
	int sumOfLeftLeaves(TreeNode* root){
		if(!root) return 0;
		queue<TreeNode*> qu;
		int ans=0;
		qu.push(root);
		while(!qu.empty()){
			TreeNode* node = qu.front();
			qu.pop();
			if(node->left&&!node->left->left&&!node->left->right){
				ans += node->left->val;
			} 
			if(node->left) qu.push(node->left);
			if(node->right) qu.push(node->right);
		}
		return ans;
	}
};

其他:

(1)依旧递归新理解:

位置 区分情况return 决定操作

(return就是当前节点类别函数意义的结果,比如这道题,如图)

(2)递归和迭代确实是两种不同的思维方式,迭代是从二叉树上挨个<揪下来>一个节点,递归则是我写一个规则,对这颗二叉树上的所有节点都适用(有点像单J、2J、3J车厘子的那个测量尺(bushi))

(3)这道题的迭代就比较简单,做判断的同时维护好迭代的队列就行

相关推荐
政企项目老覃18 小时前
大模型幻觉治理与自动评测:金融风控场景的落地实践
人工智能·算法·机器学习
淡海水18 小时前
08-03-不可变-ImmutableDictionary-TKey-TValue-与ImmutableHashSet-T-持久化哈希树
数据结构·算法·c#·哈希算法·dictionary·immutable
hansang_IR18 小时前
【题解】[APIO2023] 赛博乐园 / cyberland
c++·算法·图论
洛阳纸贵19 小时前
MATLAB-matlab基础知识
学习·算法·matlab
落羽的落羽19 小时前
【AI】快速理解AI应用的相关名词概念
linux·c++·人工智能·python·计算机网络·算法
Nil20819 小时前
leetcode 17电话号码的字母组合
算法·leetcode·职场和发展
203号居民21 小时前
LeetCode hot 100 — 25. K 个一组翻转链表
算法·leetcode·链表
ocean210321 小时前
2025-2026年AI算法与模型研发面试高频知识点洞察
人工智能·算法·面试
Nil20821 小时前
leetcode 78子集
数据结构·算法·leetcode