【宫水三叶】树的遍历运用题
递归
容易想到「递归」进行求解,在 DFS 过程中记录下当前的值为多少,假设遍历到当前节点 $x$ 前,记录的值为 $cur$,那么根据题意,我们需要先将 $cur$ 进行整体左移(腾出最后一位),然后将节点 $x$ 的值放置最低位来得到新的值,并继续进行递归。
递归有使用「函数返回值」和「全局变量」两种实现方式。
代码:
###Java
class Solution {
public int sumRootToLeaf(TreeNode root) {
return dfs(root, 0);
}
int dfs(TreeNode root, int cur) {
int ans = 0, ncur = (cur << 1) + root.val;
if (root.left != null) ans += dfs(root.left, ncur);
if (root.right != null) ans += dfs(root.right, ncur);
return root.left == null && root.right == null ? ncur : ans;
}
}
###Java
class Solution {
int ans = 0;
public int sumRootToLeaf(TreeNode root) {
dfs(root, 0);
return ans;
}
void dfs(TreeNode root, int cur) {
int ncur = (cur << 1) + root.val;
if (root.left != null) dfs(root.left, ncur);
if (root.right != null) dfs(root.right, ncur);
if (root.left == null && root.right == null) ans += ncur;
}
}
- 时间复杂度:$O(n)$
- 空间复杂度:忽略递归带来的额外空间开销,复杂度为 $O(1)$
迭代
自然也可以使用「迭代」进行求解。
为了不引入除「队列」以外的其他数据结构,当我们可以把某个节点 $x$ 放出队列时,先将其的值修改为当前遍历路径对应的二进制数。
代码:
###Java
class Solution {
public int sumRootToLeaf(TreeNode root) {
int ans = 0;
Deque<TreeNode> d = new ArrayDeque<>();
d.addLast(root);
while (!d.isEmpty()) {
TreeNode poll = d.pollFirst();
if (poll.left != null) {
poll.left.val = (poll.val << 1) + poll.left.val;
d.addLast(poll.left);
}
if (poll.right != null) {
poll.right.val = (poll.val << 1) + poll.right.val;
d.addLast(poll.right);
}
if (poll.left == null && poll.right == null) ans += poll.val;
}
return ans;
}
}
- 时间复杂度:$O(n)$
- 空间复杂度:$O(n)$
最后
如果有帮助到你,请给题解点个赞和收藏,让更多的人看到 ~ ("▔□▔)/
也欢迎你 关注我 和 加入我们的「组队打卡」小群 ,提供写「证明」&「思路」的高质量题解。
所有题解已经加入 刷题指南,欢迎 star 哦 ~



