I'm working on binary search tree homework and am asked to convert a recursive method to an iterative method. Here is the recursive method and below that is my iterative method. This method should return node containing the kth key. My method keeps giving me a NullPointerException and I'm not sure why. Thank you.
Provided code:
public Key select(int k) {
Node node = select(root, k);
if (node==null) {
return null;
} else {
return node.key;
}
}
// Return Node containing kth key (zero based)
private Node select(Node node, int k) {
if (node == null) return null;
int t = size(node.left);
if (t > k)
return select(node.left, k);
else if (t < k)
return select(node.right, k - t - 1);
else
return node;
}
My Code:
public Key selectI(int k) {
return selectI(root, k);
}
private Key selectI(Node node, int k) {
Node curr = node;
while (curr != null) {
int t = size(node.left);
if (t > k) {
curr = node.left;
} else if (t < k) {
curr = node.right;
k = (k - (t - 1));
} else
return curr.key;
}
return null;
}
The problem seems to be that you are not updating the value for k. This is normally done recursively, but you have to do it mathematically if you are going to make an iterative function. When you pass to the left (t > k) you continue searching for the node with the size of k. When you pass to the right (t < k) you are searching for a node with size k = (k - (t - 1)). Eventually t and k will either be equal or zero, in which case you've found the node you're looking for!
Also make sure that you are constantly updating the size of the current node you are looking at. You don't want to only look at the size of the tree, this ruins the mathematical relationship between your t and k values, which will cause the program to run until there are no more nodes to look at!
Related
How does this code work? (leetcode 95 question) I don't understand how the 2 recursions work inside the for loop. Does the 2nd inner for loop end when the recursive function returns NULL? Or would it continue executing the 3rd inner for loop?
class Solution {
public:
vector<TreeNode*> generateTrees(int n) {
if(n == 0) {
return {};
}
vector<TreeNode*> ans = generateT(1,n);
return ans;
}
vector<TreeNode*> generateT(int l, int r) {
if(l > r) return {nullptr};
vector<TreeNode*> ans;
for(int i=l; i <= r; ++i) {
for(TreeNode*left: generateT(l, i-1)) {
for(TreeNode* right:generateT(i+1, r)) {
ans.push_back(new TreeNode(i));
ans.back()->left = left;
ans.back()->right = right;
}
}
}
return ans;
}
};
Problem statement:
Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.
Does the 2nd inner for loop end when the recursive function returns NULL?
No. The recursive function is not returing NULL, it is returning vector of nullptr.
Or would it continue executing the 3rd inner for loop?
Of course, it will.
How does this code work? I don't understand how the 2 recursions work inside the loop.
I suppose the following snippet is the cause of confusion, so commented the case when nullptr provided by outer loop.
vector<TreeNode*> generateT(int l, int r) {
if(l > r) return { nullptr };
vector<TreeNode*> ans;
for ( int i = l; i <= r; i++ ) {
// if l = 0, i = 0
for ( TreeNode* left :generateT(l, i-1) ) // if l = 0, i = -1, returns { nullptr } (vector of nullptr)
for (TreeNode* right :generateT(i+1, r)) { // now this snippet will execute
auto node = new TreeNode(i);
ans.push_back(node);
node->left = left; // the nullptr we have from the outer loop, will provide null value for this
node->right = right;
}
}
return ans;
}
Visually, for a combination of node where,
a
\
b
/ \
null c
/
null
the above pattern occurs the provided { nullptr } from outer loop will come in handy setting left node.
I have a tree which as certain elements, I have a method essentially returns a list of elements that are within the distance.
Example
In the tree above, once I have my method, I should be able to input a data and distance. Lets say the data I input is 1 and the distance is 2. In this case, the method should output elements, [2,3,4] because I should be able to output data that is less than or equal to the given distance.
I know how to output data that have a distance of 2 away, but I am struggling to include data that includes data that is 1 away as well.
void printkdistanceNodeDown(Node node, int k)
{
if (node == null || k < 0)
return;
if (k == 0)
{
System.out.print(node.data);
System.out.println("");
return;
}
// Recur for left and right subtrees
printkdistanceNodeDown(node.left, k - 1);
printkdistanceNodeDown(node.right, k - 1);
}
int printkdistanceNode(Node node, Node target, int k)
{
if (node == null)
return -1;
if (node == target)
{
printkdistanceNodeDown(node, k);
return 0;
}
// Recur for left subtree
int dl = printkdistanceNode(node.left, target, k);
// Check if target node was found in left subtree
if (dl != -1)
{
if (dl + 1 == k)
{
System.out.print(node.data);
System.out.println("");
}
else
printkdistanceNodeDown(node.right, k - dl - 2);
// Add 1 to the distance and return value for parent calls
return 1 + dl;
}
// MIRROR OF ABOVE CODE FOR RIGHT SUBTREE
// Note that we reach here only when node was not found in left
// subtree
int dr = printkdistanceNode(node.right, target, k);
if (dr != -1)
{
if (dr + 1 == k)
{
System.out.print(node.data);
System.out.println("");
}
else
printkdistanceNodeDown(node.left, k - dr - 2);
return 1 + dr;
}
// If target was neither present in left nor in right subtree
return -1;
}
Given matrices A and B the tropical product is defined to be the usual matrix product with multiplication traded out for addition and addition traded out for minimum. That is, it returns a new matrix C such that,
C_ij = minimum(A_ij, B_ij, A_i1 + B_1j, A_i2 + B_12,..., A_im + B_mj)
Given the underlying adjacency matrix A_g of a graph g, the nth "power" with respect to the tropical product represents the connections between nodes reachable in at most n steps. That is, C_ij = (A**n)_ij has value m if nodes i and j are separated by m<=n edges.
In general, given some graph with N nodes. The diameter of the graph can only be at most N; and, given a graph with diameter k, A**n = A**k for all n>k and the matrix D_ij = A**k is called the "distance matrix" entries representing the distances between all nodes in the graph.
I have written a tropical product function in chapel and I want to write a function that takes an adjacency matrix and returns the resulting distance matrix. I have tried the following approaches to no avail. Guidance in getting past these errors would be greatly appreciated!
proc tropicLimit(A:[] real,B:[] real) {
var R = tropic(A,B);
if A == R {
return A;
} else {
tropicLimit(R,B);
}
}
which threw a domain mismatch error so I made the following edit:
proc tropicLimit(A:[] real,B:[] real) {
var R = tropic(A,B);
if A.domain == R.domain {
if && reduce (A == R) {
return R;
} else {
tropicLimit(R,B);
}
} else {
tropicLimit(R,B);
}
}
which throws
src/MatrixOps.chpl:602: error: control reaches end of function that returns a value
proc tropicLimit(A:[] real,B:[] real) {
var R = tropic(A,B);
if A.domain == R.domain {
if && reduce (A == R) { // Line 605 is this one
} else {
tropicLimit(R,B);
}
} else {
tropicLimit(R,B);
}
return R;
}
Brings me back to this error
src/MatrixOps.chpl:605: error: halt reached - Sparse arrays can't be zippered with anything other than their domains and sibling arrays (CS layout)
I also tried using a for loop with a break condition but that didn't work either
proc tropicLimit(B:[] real) {
var R = tropic(B,B);
for n in B.domain.dim(2) {
var S = tropic(R,B);
if S.domain != R.domain {
R = S; // Intended to just reassign the handle "R" to the contents of "S" i.o.w. destructive update of R
} else {
break;
}
}
return R;
}
Any suggestions?
src/MatrixOps.chpl:605: error: halt reached - Sparse arrays can't be zippered with anything other than their domains and sibling arrays (CS layout)
I believe you are encountering a limitation of zippering sparse arrays in the current implementation, documented in #6577.
Removing some unknowns from the equation, I believe this distilled code snippet demonstrates the issue you are encountering:
use LayoutCS;
var dom = {1..10, 1..10};
var Adom: sparse subdomain(dom) dmapped CS();
var Bdom: sparse subdomain(dom) dmapped CS();
var A: [Adom] real;
var B: [Bdom] real;
Adom += (1,1);
Bdom += (1,1);
A[1,1] = 1.0;
B[1,1] = 2.0;
writeln(A.domain == B.domain); // true
var willThisWork = && reduce (A == B);
// dang.chpl:19: error: halt reached - Sparse arrays can't be zippered with
// anything other than their domains and sibling arrays (CS layout)
As a work-around, I would suggest looping over the sparse indices after confirming the domains are equal and performing a && reduce. This is something you could wrap in a helper function, e.g.
proc main() {
var dom = {1..10, 1..10};
var Adom: sparse subdomain(dom) dmapped CS();
var Bdom: sparse subdomain(dom) dmapped CS();
var A: [Adom] real;
var B: [Bdom] real;
Adom += (1,1);
Bdom += (1,1);
A[1,1] = 1.0;
B[1,1] = 2.0;
if A.domain == B.domain {
writeln(equal(A, B));
}
}
/* Some day, this should be A.equals(B) ! */
proc equal(A: [], B: []) {
// You could also return 'false' if domains do not match
assert(A.domain == B.domain);
var s = true;
forall (i,j) in A.domain with (&& reduce s) {
s &&= (A[i,j] == B[i,j]);
}
return s;
}
src/MatrixOps.chpl:602: error: control reaches end of function that returns a value
This error is a result of not returning something in every condition. I believe you intended to do:
proc tropicLimit(A:[] real,B:[] real) {
var R = tropic(A,B);
if A.domain == R.domain {
if && reduce (A == R) {
return R;
} else {
return tropicLimit(R,B);
}
} else {
return tropicLimit(R,B);
}
}
I've several confusion about tail recursion as follows:
some of the recursion functions are void functions for example,
// Prints the given number of stars on the console.
// Assumes n >= 1.
void printStars(int n) {
if (n == 1) {
// n == 1, base case
cout << "*";
} else {
// n > 1, recursive case
cout << "*"; // print one star myself
printStars(n - 1); // recursion to do the rest
}
}
and another example:
// Prints the given integer's binary representation.
// Precondition: n >= 0
void printBinary(int n) {
if (n < 2) {
// base case; same as base 10
cout << n;
} else {
// recursive case; break number apart
printBinary(n / 2);
printBinary(n % 2);
}
}
As we know by definition tail recursion should return some value from tail call. But for void functions it does not return any value. By intinction I think they are tail recursion but I am not confident about it.
another question is that, if a recursion function has several logical end, should tail recursion come at all logical ends or just one of the logical ends? I saw someone argued that only one of the logical ends is OK, but I am not sure about that. Here's my example:
// Returns base ^ exp.
// Precondition: exp >= 0
int power(int base, int exp) {
if (exp < 0) {
throw "illegal negative exponent";
} else if (exp == 0) {
// base case; any number to 0th power is 1
return 1;
} else if (exp % 2 == 0) {
// recursive case 1: x^y = (x^2)^(y/2)
return power(base * base, exp / 2);
} else {
// recursive case 2: x^y = x * x^(y-1)
return base * power(base, exp - 1);
}
}
Here we have logical end as tail recursion and another one that is not tail recursion. Do you think this function is tail recursion or not? why?
I have encountered the following problem:
N is positive non-zero integer and I have to calculate the product of : N*(N-1)^2*(N-2)^3*..*1^N.
My solution so far is as follows:
N*myFact(N-1)*fact(N-1)
The thing is I'm not allowed to use any helping functions, such as 'fact()'.
EDIT: Mathematically it can be represented as follows: N!*(N-1)! (N-2)!..*1!
This function is called the superfactorial. A recursive implementation is
long superFact(n) {
if (n < 2) return 1;
long last = superFact(n-1);
long prev = superFact(n-2);
return last * last / prev * n;
}
but this is very inefficient -- it takes about 3*F(n) recursive calls to find superFact(n), where F(n) is the n-th Fibonacci number. (The work grows exponentially.)
Try:
int myFact(int n) {
return n == 1 ? 1 : myFact(n-1)*n;
}
I assume this needs to be accomplished with 1 function i.e. you're not allowed to create a fact helper function yourself.
You can use the fact that myFact(n-1) / myFact(n-2) == (n-1)!
int myFact(int n)
{
if (n == 0 || n == 1) {
return 1
} else {
// (n - 1)!
int previousFact = myFact(n - 1) / myFact(n - 2);
return myFact(n - 1) * previousFact * n;
}
}