题目6:1022. 从根到叶的二进制数之和
同类题目
无
前置知识
- 无
题目描述
给出一棵二叉树,其上每个结点的值都是 0 或 1 。每一条从根到叶的路径都代表一个从最高有效位开始的二进制数。
- 例如,如果路径为
0 -> 1 -> 1 -> 0 -> 1,那么它表示二进制数01101,也就是13。
对树上的每一片叶子,我们都要找出从根到该叶子的路径所表示的数字。
返回这些数字之和。题目数据保证答案是一个 32 位 整数。
示例 1:
输入:root = [1,0,1,0,1,0,1]
输出:22
解释:(100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
示例 2:
输入:root = [0]
输出:0
提示:
- 树中的节点数在
[1, 1000]范围内 Node.val仅为0或1
思路分析
递归法
叶子节点的判断:root->left == nullptr && root->right == nullprt
如果是叶子节点,则返回 root->val,如果是非叶子节点,则调用递归函数返回左右子树的和。
思考:为什么下面的递归调用中val 值,不需要回溯?
程序代码
class Solution {
public:
int travel(TreeNode *root, int val) {
if (root == nullptr) {
return 0;
}
// val = val*2 + root->val;
val = (val << 1) | root->val;
// 当为叶子节点时,直接返回
if (root->left == nullptr && root->right == nullptr) {
return val;
}
// 这里是点睛之笔,可以和我下面的回溯代码进行比较,为什么这里的val 不需要回溯?
return dfs(root->left, val) + dfs(root->right, val);
}
int sumRootToLeaf(TreeNode* root) {
return travel(root, 0);
}
};
为什么下面的递归调用中val 值,不需要回溯?一张图说明一下问题
思路分析
回溯法:
使用一个全局数组,记录遍历到当前节点时数组中的二进制的值,需要时时刻刻记住,进入递归函数添加,退出递归时删除。
程序代码
//https://leetcode.cn/problems/sum-of-root-to-leaf-binary-numbers/description/
//1022. 从根到叶的二进制数之和
#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
private:
int sum = 0;
vector<int> s;
public:
// 二进制转成十进制的结果
void cal(vector<int> &s)
{
for(int i=s.size()-1;i>=0;i--)
{
sum += s[i]*pow(2,s.size()-i-1);
}
}
void travel(TreeNode* root)
{
if(root == nullptr)
{
return;
}
// 叶子节点,进行计算
if(root->left == nullptr && root->right == nullptr)
{
s.push_back(root->val);
cal(s);
// 别忘记回溯
s.pop_back();
return;
}
s.push_back(root->val);
travel(root->left);
travel(root->right);
// 别忘记回溯
s.pop_back();
}
int sumRootToLeaf(TreeNode* root) {
travel(root);
return sum;
}
};
题目感悟
通过此题,可以加深对回溯法和递归法的理解。什么时候需要回溯,什么时候不需要回溯,此刻的你是否理解通透。
更多相关知识:github.com/pingguo1987…