递归的参数与返回值还是不一样-LCR 049. 求根节点到叶节点数字之和
https://leetcode.cn/problems/3Etpl5/submissions/751931194/
通过这个题看不同dfs的写法:
1 这层递归时的结果,究竟是算不算这一层的,是上一层的还是这一层的
2 参数与返回值的区别用法
参数适合“从上往下”传信息
父节点计算好的状态,传给子节点。
返回值适合“从下往上”传信息
例如求二叉树高度:
int dfs(TreeNode* root) {
if (!root) return 0;
int left = dfs(root->left);
int right = dfs(root->right);
return max(left, right) + 1;
}
以后看到递归题,可以想:“这个信息是谁算出来的,谁需要它。”父节点已经知道,子结点需要 vs 子结点计算出来,父节点需要.
放几个写法:
1 最容易想的dfs,算当前结点值,全局变量记录结果.
class Solution {
private:
int res = 0;
void dfs(TreeNode* root, int curS) {
if (!root) {return ;}
if (!root->left && !root->right) {res += curS; return;}
if (root->left)
dfs(root->left, 10*curS+root->left->val);
if (root->right)
dfs(root->right, 10*curS+root->right->val);
}
public:
int sumNumbers(TreeNode* root) {
dfs(root, root->val);
return res;
}
};
2 最容易想的dfs,记录上一层的结点值,全局变量记录结果.
class Solution {
private:
int res = 0;
void dfs(TreeNode* root, int curS) {
if (!root) {return ;}
if (!root->left && !root->right) {res += 10*curS+root->val; return;}
dfs(root->left, 10*curS+root->val);
dfs(root->right, 10*curS+root->val);
}
public:
int sumNumbers(TreeNode* root) {
dfs(root, 0);
return res;
}
};
3 返回值记录最终结果,参数记录从上到下的状态结果:
class Solution {
public:
int dfs(TreeNode* root, int curS) {
curS = curS * 10 + root->val;
if (!root->left && !root->right) {
return curS;
}
int res = 0;
if (root->left)
res += dfs(root->left, curS);
if (root->right)
res += dfs(root->right, curS);
return res;
}
int sumNumbers(TreeNode* root) {
return dfs(root, 0);
}
};
此外,还有bfs,结合前缀和的思想,思路简单:
class Solution {
private:
typedef struct E {
TreeNode* node = nullptr;
int val = 0;
E(TreeNode* n, int v): node(n), val(v){};
E(){};
}E;
queue<E> q;
int res = 0;
public:
int sumNumbers(TreeNode* root) {
if (!root) {return 0;}
q.push(E(root, root->val));
while(!q.empty()) {
int layersize = q.size();
for (int i = 0; i < layersize; i++) {
E t = q.front();
q.pop();
if (t.node->left) {
q.push(E(t.node->left, t.val*10+t.node->left->val));
}
if (t.node->right) {
q.push(E(t.node->right, t.val*10+t.node->right->val));
}
if (!t.node->left && !t.node->right) {res += t.val;}
}
}
return res;
}
};
这个题把while中的for去掉也行,不必一定分开每一层。但是这样更规范吧。

浙公网安备 33010602011771号