Condition statement not clear t->item - conditional-statements

I have got a got a code to search through a binary search tree, and i can't understand the t->item in the if conditions.
search(item, t) {
if (t == NULL) // t is an empty tree
{item is not present in tree, t, and terminate search }
else if (item == t->item)
{item is present in tree, t, and terminate search}
else if (item < t->item)
{search in left subtree (i.e. t->left) recursively}
else
{search in right subtree (i.e. t->right) recursively}
}
Can someone explain this to me?

item == t->item means "if item is the root of the tree". Otherwise, you'll look whether if it's greater or less than the root to see if you're continuing to search in the left or in the right subtree.

Related

Binary search tree (BST) inorder visit that prints "The BST is in order"

I am currently working on a Binary Search Tree project, and I would like to implement an "inorder" visit function:
void inorder(struct node *root)
{
if(root!=NULL) // checking if the root is not null
{
inorder(root->left_child); // visiting left child
printf(" %d ", root->data); // printing data at root
inorder(root->right_child);// visiting right child
}
}
However I do have a little issue, my BST varies between 100000 and 1000000 keys, and as you can imagine, printing them all is not very "handy". Is there perhaps a way to modify this inorder function in a way that it only prints "The BST is in order"? I have been trying to implement it but I really can't find a solution.
Thanks in advance for your help! Wish you a lovely coding session!
It looks like you want to verify whether a tree is actually a valid BST, i.e. its in-order traversal would visit its values in non-decreasing order.
For that you need a different function. Here is how it could be done:
int isValidBstHelper(struct node *root, int low, int high) {
return root == NULL ||
(root->data >= low && root->data <= high &&
isValidBstHelper(root->left_child, low, root->data) &&
isValidBstHelper(root->right_child, root->data, high));
}
int isValidBst(struct node *root) {
return isValidBstHelper(root, INT_MIN, INT_MAX);
}
isValidBst will return 1 when the tree is a valid BST and 0 when it is not.
To print the result, just call like this:
if (isValidBst(root)) {
printf("The tree is a valid BST");
} else {
printf("The tree is NOT a valid BST");
}

Check for a value in Kotlin immutable list

I need to condense the following lines in kotlin to a more elegant way. I'm not able to figure out how to check the optional and the values at the same time. Basically I need to verify the list 'a' exists, has one or more items and that they are not 0.
val a = Utils.getItems() // returns an Optional<ImmutableList<ItemChange>>
if(!a.orElse(ImmutableList.of()).size > 0) {
val nonZero = a.get().filter { it.item != BigDecimal.ZERO }
return nonZero.size > 0
}
Assuming you also want to return false if non-existent or size 0, this is how I'd do it.
The any function returns true if any value matches, so it already takes care of the case of an empty list. And it breaks immediately if any match is found, whereas filter will exhaustively check the whole List and allocate a new List to hold the results.
Guava Optional can simply be converted to nullable with orNull() because Kotlin already has null-safety built in.
val items = Utils.getItems().orNull()
return items != null && items.any { it.item != BigDecimal.ZERO }

Binary Search Tree Iterator java

I did the LeetCode question Binary Search Tree Iterator. the following code is what I learned from others. One part I didn't understand which is cur = cur.right. Since I got the smallest value of cur.val. Why do I need to assign cur.right to cur? When I remove cur = cur.right, it said time limit exceeded. Could someone can help me to explain it?
public class BSTIterator {
Stack<TreeNode> stack;
TreeNode cur;
public BSTIterator(TreeNode root) {
stack = new Stack<>();
cur = root;
}
/** #return the next smallest number */
public int next() {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
int val = cur.val;
cur = cur.right; //why needed to assign cur.right to cur?
return val;
}
}
By thinking on the structure of a binary search tree we know that the left node is less than the parent (or middle) node, and that the right node is more than the parent (or middle) node. By setting the current node to be equal to the right node you are iterating through the tree in order from least to largest value. Note that if cur.right() doesn't exist then cur will be set to null and therefore not execute the while loop.
I submitted my code, it was successful.
https://leetcode.com/problems/binary-search-tree-iterator/
You can find it here.
https://github.com/yan-khonski-it/bst/blob/master/bst-core/src/main/java/com/yk/training/bst/iterators/BSTIterator.java
Explanation.
You have to use inorder which first visits the left sub-tree, then visit the current node, and then the right sub-tree, so you will iterate through all the elements in the ascending order.
Now, you have stack, which holds all the node that you should return in next call in the correct order.
next will remove the last element from the stack. Now you check the current node, if it has right subtree. If so, you need to iterate though left elements of the right subtree.
/**
* Find next node to be returned in {#link #next()}.
* Push it to stack.
*/
public void navigateLeftSubtree() {
stack.push(currentNode);
while (currentNode.left != null) {
currentNode = currentNode.left;
stack.push(currentNode);
}
}
In this case, (right sub tree is present for current node), you should put the right child of the current node into the stack. You don't want to put the current into the stack, if you have already visited it.
public int next() {
currentNode = stack.pop();
final int currentValue = currentNode.value;
if (currentNode.right != null) {
// Push root of the right subtree into stack.
currentNode = currentNode.right;
navigateLeftSubtree();
}
return currentValue;
}

Alternative to nested if for conditional logic

Is there a design pattern or methodology or language that allows you to write complex conditional logic beyond just nested Ifs?
At the very least, does this kind of question or problem have a name? I was unable to find anything here or through Google that described what I was trying to solve that wasn't just, replace your IF with a Switch statement.
I'm playing around with a script to generate a bunch of data. As part of this, I'd like to add in a lot of branching conditional logic that should provide variety as well as block off certain combinations.
Something like, If User is part of group A, then they can't be part of group B, and if they have Attribute C, then that limits them to characteristic 5 or 6, but nothing below or above that.
The answer is simple: refactoring.
Let's take an example (pseudo-code):
if (a) {
if (b) {
if (c) {
// do something
}
}
}
can be replaced by:
if (a && b && c) {
// do something
}
Now, say that a, b and c are complex predicates which makes the code hard to read, for example:
if (visitorIsInActiveTestCell(visitor) &&
!specialOptOutConditionsApply(request, visitor) &&
whatEverWeWantToCheckHere(bla, blabla)) {
// do something
}
we can refactor it as well and create a new method:
def shouldDoSomething(request, visitor, bla, blabla) {
return visitorIsInActiveTestCell(visitor) &&
!specialOptOutConditionsApply(request, visitor) &&
whatEverWeWantToCheckHere(bla, blabla)
}
and now our if condition isn't nested and becomes easier to read and understand:
if (shouldDoSomething(request, visitor, bla, blabla)) {
// do something
}
Sometimes it's not straightforward to extract such logic and refactor, and it may require taking some time to think about it, but I haven't yet ran into an example in which it was impossible.
All of the foregoing answers seem to miss the question.
One of the patterns that frequently occurs in hardware-interface looks like this:
if (something) {
step1;
if ( the result of step1) {
step2;
if (the result of step2) {
step3;
... and so on
}}}...
This structure cannot be collapsed into a logical conjunction, as each step is dependent on the result of the previous one, and may itself have internal conditions.
In assembly code, it would be a simple matter of test and branch to a common target; i.e., the dreaded "go to". In C, you end up with a pile of indented code that after about 8 levels is very difficult to read.
About the best that I've been able to come up with is:
while( true) {
if ( !something)
break;
step1
if ( ! result of step1)
break;
step2
if ( ! result of step2)
break;
step3
...
break;
}
Does anyone have a better solution?
It is possible you want to replace your conditional logic with polymorphism, assuming you are using an object-oriented language.
That is, instead of:
class Bird:
#...
def getSpeed(self):
if self.type == EUROPEAN:
return self.getBaseSpeed();
elif self.type == AFRICAN:
return self.getBaseSpeed() - self.getLoadFactor() * self.numberOfCoconuts;
elif self.type == NORWEGIAN_BLUE:
return 0 if isNailed else self.getBaseSpeed(self.voltage)
else:
raise Exception("Should be unreachable")
You can say:
class Bird:
#...
def getSpeed(self):
pass
class European(Bird):
def getSpeed(self):
return self.getBaseSpeed()
class African(Bird):
def getSpeed(self):
return self.getBaseSpeed() - self.getLoadFactor() * self.numberOfCoconuts
class NorwegianBlue(Bird):
def getSpeed():
return 0 if self.isNailed else self.getBaseSpeed(self.voltage)
# Somewhere in client code
speed = bird.getSpeed()
Taken from here.

Deleting the maximum element in BST

Some of the code below seems too obvious, traversing the tree using its right most branch since that is where all the max values are.However, I don't understand a few things about this code I saw in Robert Sedgewick's Algorithms book.
public void deleteMax() {
if (isEmpty()) throw new NoSuchElementException("");
root = deleteMax(root);
assert check();
}
private Node deleteMax(Node x) {
if (x.right == null) return x.left;
x.right = deleteMax(x.right);
x.size = size(x.left) + size(x.right) + 1;
return x;
}
In the private method why do we return the left element if the right child of x is null ?From my understanding x would be the maximum if x has no right children and is the right most node we could go to.Also I don't understand when do we return x in the last line of the 2nd method.
If x doesn't have a right child then x is the maximum node. We "delete" it by returning x.left (the new max node). We return x after we've modified its right subtree.