【题目】
给出一棵二叉树,其上每个结点的值都是 0 或 1 ,每一条从根到叶的路径都代表一个从最高有效位开始的二进制数,例如,如果路径为 0 -> 1 -> 1 -> 0 -> 1,那么它表示二进制数 01101,也就是 13,对树上的每一片叶子,我们都要找出从根到该叶子的路径所表示的数字,以 10^9 + 7 为模,返回这些数字之和。
来源:leetcode
链接:https://leetcode-cn.com/problems/sum-of-root-to-leaf-binary-numbers/
【示例】
输入:[1,0,1,0,1,0,1]
输出:22
解释:(100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
【提示】
树中的结点数介于 1 和 1000 之间
node.val 为 0 或 1
【代码】
【迭代法一】
/**
* 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 {
private:
int sum=0;
stack<TreeNode*> s,s2;
public:
void deal(){
while(!s.empty()){
s2.push(s.top());
s.pop();
}
int calc=0;
while(!s2.empty()){
s.push(s2.top());
calc=calc*2+s2.top()->val;
s2.pop();
}
sum+=calc;
}
int sumRootToLeaf(TreeNode* root) {
TreeNode*node=root,*last=NULL;
while(!s.empty()||node){
while(node){
s.push(node);
node=node->left;
}
if(!s.empty()){
node=s.top();
if(node->right&&node->right!=last)
node=node->right;
else{
if(node->left==NULL&&node->right==NULL)
deal();
s.pop();
last=node;
node=NULL;
}
}
}
return sum;
}
};
【迭代法二】
/**
* 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) {
if(root==NULL)
return 0;
pair<TreeNode*,int> node=pair<TreeNode*,int>(root,root->val);
stack<pair<TreeNode*,int>> s;
s.push(node);
int sum=0;
while(!s.empty()){
node=s.top();
s.pop();
if(node.first->left==NULL&&node.first->right==NULL)
sum+=node.second;
if(node.first->left)
s.push(pair<TreeNode*,int>(node.first->left,node.second*2+
node.first->left->val));
if(node.first->right)
s.push(pair<TreeNode*,int>(node.first->right,node.second*2+
node.first->right->val));
}
return sum;
}
};
【递归法】
/**
* 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 {
private:
int sum=0;
public:
void preOrder(TreeNode* root,int num){
if(root->left==NULL&root->right==NULL){
sum+=num;
return;
}
if(root->left)
preOrder(root->left,num*2+root->left->val);
if(root->right)
preOrder(root->right,num*2+root->right->val);
}
int sumRootToLeaf(TreeNode* root) {
if(root==NULL)
return 0;
preOrder(root,root->val);
return sum;
}
};