题目
给出一棵二叉树,其上每个结点的值都是 0 或 1 。每一条从根到叶的路径都代表一个从最高有效位开始的二进制数。例如,如果路径为 0 -> 1 -> 1 -> 0 -> 1,那么它表示二进制数 01101,也就是 13 。
对树上的每一片叶子,我们都要找出从根到该叶子的路径所表示的数字。
以 10^9 + 7 为模,返回这些数字之和。
示例:

输入:[1,0,1,0,1,0,1]
输出:22
解释:(100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-of-root-to-leaf-binary-numbers
解题思路
没有弄懂题目里面的模是什么意思,不过按示例的意思,结果返回这些二进制数转换成十进制之后的和。
本题与题目257.二叉树的所有路径类似,主要考察树的中序遍历。257额外考察一点string的知识,本题额外考察一点二进制的知识。
正好257介绍的是非递归思路,所以这里介绍递归思路。
- 1.递归结束条件:root==NULL
- 2.递归过程中要做的事情:
- a.记录每个结点的值,并将值按遍历顺序排列成二进制数;
- b.将满足要求的值加到结果中;
- 3.递归顺序:先左后右
知识点总结
二进制操作符:左移<< 相当于乘2 右移>> 相当于除2
二进制转十进制的公式:binary=(binary<<1)|root->val;
参考:C++二进制操作符
代码(C++)
递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void dfs(TreeNode* root,int binary,int &res){
if(root==NULL) return ;
binary=(binary<<1)|root->val;
if(root->left==NULL&&root->right==NULL){
res+=binary;
}
dfs(root->left,binary,res);
dfs(root->right,binary,res);
}
int sumRootToLeaf(TreeNode* root) {
int res=0;
int binary=0;
dfs(root,binary,res);
return res;
}
};
非递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumRootToLeaf(TreeNode* root) {
stack<pair<TreeNode*,int>> st;
int binary=0;
int res=0;
while(!st.empty()||root){
while(root){
binary=(binary<<1)|root->val;
st.push(pair(root,binary));
root=root->left;
}
binary=st.top().second;
root=st.top().first;
st.pop();
if(root->left==NULL&&root->right==NULL){
res+=binary;
}
root=root->right;
}
return res;
}
};
这篇博客介绍了LeetCode第1022题,要求求解从二叉树根节点到叶子节点的所有路径所表示的二进制数之和,模10^9 + 7。博主分享了对题目的理解、解题思路和递归解决方案,特别强调了如何进行二进制操作和中序遍历。
376

被折叠的 条评论
为什么被折叠?



