File tree 1 file changed +84
-0
lines changed
1 file changed +84
-0
lines changed Original file line number Diff line number Diff line change
1
+ ![ ] ( https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png )
2
+ > 仰望星空的人,不应该被嘲笑
3
+
4
+ ## 题目描述
5
+
6
+ 计算给定二叉树的所有左叶子之和。
7
+
8
+ 示例:
9
+
10
+ ``` javascript
11
+ 3
12
+ / \
13
+ 9 20
14
+ / \
15
+ 15 7
16
+
17
+ 在这个二叉树中,有两个左叶子,分别是 9 和 15 ,所以返回 24
18
+ ```
19
+
20
+ 来源:力扣(LeetCode)
21
+ 链接:https://leetcode-cn.com/problems/sum-of-left-leaves
22
+ 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
23
+
24
+
25
+
26
+ ## 解题思路
27
+
28
+ ` dfs ` ,求左叶子之和,叶子结点我们比较好判断,而对于左孩子,我们设置一个标记就好了,例如左孩子标记 ` 1 ` ,右孩子标记 ` 0 ` ,那么当且仅当是叶子节点,并且标记为 ` 1 ` (即左孩子)时,我们进行累加求和。
29
+
30
+ ``` javascript
31
+ /**
32
+ * Definition for a binary tree node.
33
+ * function TreeNode(val) {
34
+ * this.val = val;
35
+ * this.left = this.right = null;
36
+ * }
37
+ */
38
+ /**
39
+ * @param {TreeNode} root
40
+ * @return {number}
41
+ */
42
+ var sumOfLeftLeaves = function (root ) {
43
+ if (! root) return 0 ;
44
+ let res = 0 ;
45
+ let dfs = (cur ,root ) => {
46
+ // 判断是叶子节点并且是左子树
47
+ if (! root .left && ! root .right && cur) {
48
+ res += root .val ;
49
+ return ;
50
+ }
51
+ // 先遍历左子树在遍历右子树
52
+ // 设置cur为1代表是左子树,为0代表右子树
53
+ root .left && dfs (1 ,root .left );
54
+ root .right && dfs (0 ,root .right );
55
+ }
56
+ dfs (0 ,root);
57
+ return res;
58
+ };
59
+ ```
60
+
61
+
62
+
63
+
64
+ ## 最后
65
+ 文章产出不易,还望各位小伙伴们支持一波!
66
+
67
+ 往期精选:
68
+
69
+ <a href =" https://github.com/Chocolate1999/Front-end-learning-to-organize-notes " >小狮子前端の笔记仓库</a >
70
+
71
+ <a href =" https://github.com/Chocolate1999/leetcode-javascript " >leetcode-javascript:LeetCode 力扣的 JavaScript 解题仓库,前端刷题路线(思维导图)</a >
72
+
73
+ 小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you!
74
+
75
+
76
+ <a href =" https://yangchaoyi.vip/ " >访问超逸の博客</a >,方便小伙伴阅读玩耍~
77
+
78
+ ![ ] ( https://img-blog.csdnimg.cn/2020090211491121.png#pic_center )
79
+
80
+ ``` javascript
81
+ 学如逆水行舟,不进则退
82
+ ```
83
+
84
+
You can’t perform that action at this time.
0 commit comments