11---
2- title : 1022.从根到叶的二进制数之和
2+ title : 1022.从根到叶的二进制数之和:DFS或BFS
33date : 2022-05-30 10:52:40
4- tags : [题解, LeetCode, 简单, 二叉树, 树, 交互, 模拟 ]
4+ tags : [题解, LeetCode, 简单, 二叉树, 树, 模拟, 深度优先搜索, DFS, 广度优先搜索, BFS, 递归, 位运算 ]
55categories : [题解, LeetCode]
6+ index_img : https://assets.leetcode.com/uploads/2019/04/04/sum-of-root-to-leaf-binary-numbers.png
67---
78
8- # 【LetMeFly】1022.从根到叶的二进制数之和
9+ # 【LetMeFly】1022.从根到叶的二进制数之和:DFS或BFS
910
1011力扣题目链接:[ https://leetcode.cn/problems/sum-of-root-to-leaf-binary-numbers/ ] ( https://leetcode.cn/problems/sum-of-root-to-leaf-binary-numbers/ )
1112
@@ -44,12 +45,12 @@ categories: [题解, LeetCode]
4445
4546二进制的100等于十进制的4
4647
47- # 思路
48-
49- 我们只需要层次遍历这棵树,遍历到某个节点时,如果存在子节点,子节点就加上这个节点的“值的<<1”的结果
48+ # 解题方法
5049
5150## 方法一:层次遍历
5251
52+ 我们只需要层次遍历这棵树,遍历到某个节点时,如果存在子节点,子节点就加上这个节点的“值的<<1”的结果
53+
5354+ 时间复杂度$O(n)$,其中$n$是树中节点的数量
5455+ 空间复杂度$O(n)$
5556
@@ -58,6 +59,9 @@ categories: [题解, LeetCode]
5859#### C++
5960
6061``` cpp
62+ /*
63+ * @LastEditTime: 2022-05-30 10:50:08
64+ */
6165class Solution {
6266public:
6367 int sumRootToLeaf(TreeNode* root) { // 不会为空
@@ -86,5 +90,58 @@ public:
8690};
8791```
8892
89- > 同步发文于CSDN,原创不易,转载请附上[原文链接](https://blog.letmefly.xyz/2022/05/30/LeetCode%201022.%E4%BB%8E%E6%A0%B9%E5%88%B0%E5%8F%B6%E7%9A%84%E4%BA%8C%E8%BF%9B%E5%88%B6%E6%95%B0%E4%B9%8B%E5%92%8C)哦~
90- > Tisfy:[https://letmefly.blog.csdn.net/article/details/125043202](https://letmefly.blog.csdn.net/article/details/125043202)
93+ ## 方法二:深度优先搜索DFS
94+
95+ 使用一个类中的“全局变量”$ans$记录所有路径数字之和,写一个DFS函数:
96+
97+ ```cpp
98+ void dfs(TreeNode* root, int now)
99+ ```
100+
101+ 其中` now ` 代表该走节点` root ` 时已经走过路径的二进制值。
102+
103+ 首先更新走到当前节点后的路径值` now = now << 1 + root->val ` ,如果` root ` 为叶节点则将该路径值累加到$ans$,否则继续递归左右子中非空的节点。
104+
105+ + 时间复杂度$O(n)$,其中$n$是树中节点的数量
106+ + 空间复杂度$O(n)$
107+
108+ ### AC代码
109+
110+ #### C++
111+
112+ ``` cpp
113+ /*
114+ * @LastEditTime: 2026-02-24 21:37:38
115+ */
116+ class Solution {
117+ private:
118+ int ans;
119+
120+ // @input.root not empty
121+ void dfs(TreeNode* root, int now) {
122+ now <<= 1;
123+ now += root->val;
124+ if (!root->left && !root->right) {
125+ ans += now;
126+ return;
127+ }
128+ if (root->left) {
129+ dfs (root->left, now);
130+ }
131+ if (root->right) {
132+ dfs(root->right, now);
133+ }
134+ }
135+ public:
136+ int sumRootToLeaf(TreeNode* root) {
137+ ans = 0;
138+ dfs(root, 0);
139+ return ans;
140+ }
141+ };
142+
143+ ```
144+
145+ > 同步发文于[CSDN](https:// letmefly.blog.csdn.net/article/details/125043202)和我的[个人博客](https://blog.letmefly.xyz/),原创不易,转载经作者同意后请附上[原文链接](ttps://blog.letmefly.xyz/2022/05/30/LeetCode%201022.%E4%BB%8E%E6%A0%B9%E5%88%B0%E5%8F%B6%E7%9A%84%E4%BA%8C%E8%BF%9B%E5%88%B6%E6%95%B0%E4%B9%8B%E5%92%8C)哦~
146+ >
147+ > 千篇源码题解[已开源](https:// github.com/LetMeFly666/LeetCode)
0 commit comments