Recursive solutions become easy if the methods keep using/updating a global variables but it become complex when you need to pass that variable onto recursion stack.
Following is a recursive solution(java) for a leetcode problem 250. Count Univalue Subtrees.
You can refer to the problem for a better understanding. My solution works just fine. I want to avoid using the global variable.
Problem statement:
Given the root of a binary tree, return the number of uni-value subtrees. A uni-value subtree means all nodes of the subtree have the same value.
- Example 1
Input: root = [5,1,5,5,5,null,5]
Output: 4
- Example 2
Input: root = []
Output: 0
- Example 3
Input: root = [5,5,5,5,5,null,5]
Output: 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;
}
}
In above recursive function recurseAndUpdate(TreeNode root), class variable uniCount is being updated depending upon some constraints.
How can I get rid of using this global variable nd come up a solution like recurseAndUpdate(TreeNode root, int uniCount) ? How can deduce the approach for such recursive logic that tends to pass some value in nested recursive call?