【发布时间】:2022-01-22 08:33:45
【问题描述】:
如果方法继续使用/更新全局变量,递归解决方案变得容易,但当您需要将该变量传递到递归堆栈时,它变得复杂。
以下是leetcode问题250. Count Univalue Subtrees的递归解决方案(java)。
您可以参考问题以获得更好的理解。我的解决方案工作得很好。我想避免使用全局变量。
问题陈述:
给定二叉树的根,返回单值子树的数量。 单值子树意味着子树的所有节点都具有相同的值。
- 示例 1
输入:root = [5,1,5,5,5,null,5]
输出:4
- 示例 2
输入:root = []
输出:0
- 示例 3
输入:root = [5,5,5,5,5,null,5]
输出:6
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int uniCount; // class level variable to keep the count of uni-valued tree/sub-tree
public int countUnivalSubtrees(TreeNode root) {
uniCount = 0;
recurseAndUpdate(root);
return uniCount;
}
private boolean recurseAndUpdate(TreeNode root) {
if (root == null) {
return true;
}
if (root.left == null && root.right == null) { // If root is a leaf node
uniCount++;
return true;
} else if (root.left == null && root.right != null) { // If root has only right child
boolean currRes = root.val == root.right.val;
boolean rightRes = recurseAndUpdate(root.right);
if (currRes && rightRes) {
uniCount++;
return true;
}
} else if (root.left != null && root.right == null) { // If root has only left child
boolean currRes = root.val == root.left.val;
boolean leftRes = recurseAndUpdate(root.left);
if (currRes && leftRes) {
uniCount++;
return true;
}
} else { // If root have both the left & right child
boolean currRes = root.val == root.left.val && root.val == root.right.val;
boolean leftRes = recurseAndUpdate(root.left);
boolean rightRes = recurseAndUpdate(root.right);
if (currRes && leftRes && rightRes) {
uniCount++;
return true;
}
}
return false;
}
}
在上述递归函数 recurseAndUpdate(TreeNode root) 中,类变量 uniCount 正在根据某些约束进行更新。
我怎样才能摆脱使用这个全局变量并想出像 recurseAndUpdate(TreeNode root, int uniCount) 这样的解决方案?对于这种倾向于在嵌套递归调用中传递一些值的递归逻辑,如何推导出方法?
【问题讨论】:
-
在参数列表中传递您需要的内容。永远不要使用全局状态。
-
是的,这就是我想要做的。你能想出一个解决方案,或者编辑上面的那个。
-
@nathan-hughes 我已将链接添加到实际问题。看看这是否有意义。
标签: java algorithm recursion binary-tree