Why is this implementation for checking balanced binary tree wrong - data-structures

public boolean isBalanced(TreeNode root) {
if(root == null) return true;
int rightCount = maxDepth(root.right);
int leftCount = maxDepth(root.left);
if(Math.abs(rightCount-leftCount)<=1) return true;
return false;
}
public int maxDepth(TreeNode root){
if(root == null) return 0;
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
Checking the max depth for both branches and determining if the absolute value is <=1

At first:
If you have invalid root arg isBalanced returns true, so that is bad implementation, despite the fact that code could have no errors.
In my opinion, function should work with valid arguments, otherwise throw exception (error?).
Also check this solution, read code and try to do something like this:
/* C program to check if a tree is height-balanced or not */
#include <stdio.h>
#include <stdlib.h>
#define bool int
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node {
int data;
struct node* left;
struct node* right;
};
/* Returns the height of a binary tree */
int height(struct node* node);
/* Returns true if binary tree with root as root is height-balanced */
bool isBalanced(struct node* root)
{
int lh; /* for height of left subtree */
int rh; /* for height of right subtree */
/* If tree is empty then return true */
if (root == NULL)
return 1;
/* Get the height of left and right sub trees */
lh = height(root->left);
rh = height(root->right);
if (abs(lh - rh) <= 1 && isBalanced(root->left) && isBalanced(root->right))
return 1;
/* If we reach here then tree is not height-balanced */
return 0;
}
/* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */
/* returns maximum of two integers */
int max(int a, int b)
{
return (a >= b) ? a : b;
}
/* The function Compute the "height" of a tree. Height is the
number of nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(struct node* node)
{
/* base case tree is empty */
if (node == NULL)
return 0;
/* If tree is not empty then height = 1 + max of left
height and right heights */
return 1 + max(height(node->left), height(node->right));
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
int main()
{
struct node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->left->left->left = newNode(8);
if (isBalanced(root))
printf("Tree is balanced");
else
printf("Tree is not balanced");
getchar();
return 0;
}
(copy & pasted from here)

Related

Why is my create function of binary search tree not working?

The create function is supposed to ask the user how many nodes they want to enter and then insert that many elements one by one.
I am using the pre order traversal function to check the creation of the binary search tree
The code runs fine for the input part, where it is asking the user for data to enter, but when it is supposed to show the tree in pre order traversal manner, it does not do anything and exits.
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
void insert(struct Node* root, int x)
{
if(root -> left == NULL && x < root -> data)
{
struct Node* new_node = (struct Node* )malloc(sizeof(struct Node));
new_node -> data = x;
new_node -> left = NULL;
new_node -> right = NULL;
root -> left = new_node;
}
else if(root -> right == NULL && x > root -> data)
{
struct Node* new_node = (struct Node* )malloc(sizeof(struct Node));
new_node -> data = x;
new_node -> left = NULL;
new_node -> right = NULL;
root -> right = new_node;
}
else
{
if(x < root -> data)
{
insert(root -> left, x);
}
else if(x > root -> data)
{
insert(root -> right, x);
}
}
}
void create(struct Node* root)
{
root = (struct Node*)malloc(sizeof(struct Node));
printf("\nHow many nodes do you want to create: ");
int tree_size;
scanf("%d", &tree_size);
printf("\nEnter data for root node: ");
int ent_data;
scanf("%d", &ent_data);
root -> data = ent_data;
root -> left = NULL;
root -> right = NULL;
for(int i=1; i<tree_size; i++)
{
printf("\nEnter data for node: ");
scanf("%d", &ent_data);
insert(root, ent_data);
}
}
void preOrderTraversal(struct Node *root)
{
if(root != NULL)
{
printf("%d, ", root -> data);
preOrderTraversal(root -> left);
preOrderTraversal(root -> right);
}
}
int main()
{
struct Node* root = NULL;
create(root);
preOrderTraversal(root);
return 0;
}
The problem is that create is not going to modify your main's variable root. C arguments are passed by value, so you should do one of the following:
Pass the address of root to the create function, or
Don't pass root as argument at all, but let create return the root pointer.
The second option is to be preferred, because root does not serve as input value for create, but as output.
Not related to your issue, but try to avoid code repetition. There are three places in your code where you call malloc and initialise a node. instead create a function for that and call it at those three places.
Here is the adapted code:
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
// Function to call whenever you need a node instance
struct Node * create_node(int x)
{
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node -> data = x;
new_node -> left = NULL;
new_node -> right = NULL;
return new_node;
}
void insert(struct Node* root, int x)
{
if(root -> left == NULL && x < root -> data)
{
root -> left = create_node(x); // Use function
}
else if(root -> right == NULL && x > root -> data)
{
root -> right = create_node(x); // Use function
}
else
{
if(x < root -> data)
{
insert(root -> left, x);
}
else if(x > root -> data)
{
insert(root -> right, x);
}
}
}
struct Node* create() // No parameter, but return type
{
printf("\nHow many nodes do you want to create: ");
int tree_size;
scanf("%d", &tree_size);
printf("\nEnter data for root node: ");
int ent_data;
scanf("%d", &ent_data);
struct Node* root = create_node(ent_data); // Use function
for(int i=1; i<tree_size; i++)
{
printf("\nEnter data for node: ");
scanf("%d", &ent_data);
insert(root, ent_data);
}
return root; // Return the root
}
void preOrderTraversal(struct Node *root)
{
if(root != NULL)
{
printf("%d, ", root -> data);
preOrderTraversal(root -> left);
preOrderTraversal(root -> right);
}
}
int main()
{
struct Node* root = create(); // No argument, but return value
preOrderTraversal(root);
return 0;
}

I need to design an algorithm to return the number of nodes in a binary tree that have two children

I have come across this question to design an algorithm to count the number of nodes in a binary tree that has two children. It was mentioned that the solution should be expressed as a pair of functions(not BST member functions).
So far I could not arrive at a concrete solution and specially the part where the solution should be expressed as a pair of non BST member functions is going over my head.
//count the number of node that has got 2 children
function countNodes(nodeElement,nodeNumber){
var nodeNumber = 0;
var children = nodeElement.children;
for(var c=0;c<children ;c++){
//check if current node has got two childs
if(getNodeChildren(children[c])==2){
nodeNumber++;
}
//recursively check if children nodes has got 2 children
nodeNumber += countNodes(children[c],nodeNumber)
}
return nodeNumber;
}
//recursively counts the number of children that a node has got
function getNodeChildren(nodeElement){
//check if is a leaf
if(nodeElement.children == 0){
return 1;
}
else {
var nodeNumber = 0;
var children = nodeElement.children;
for(var c=0;c<children ;c++){
nodeNumber += getNodeChildren(children[c],nodeNumber+1);
}
return nodeNumber;
}
}
Assuming Node is a struct containing two pointers to Node, named left and right:
int count_2_ch_nodes(Node* root)
{
if (root == NULL) return 0;
// Recursively count the number of nodes that are below
// this node that have two children:
int count = 0;
if (root->left != NULL) count += count_2_ch_nodes(root->left);
if (root->right != NULL) count += count_2_ch_nodes(root->right);
// Add this node IF it has 2 children:
if (has_2_ch(root)) count++;
return count;
}
/* Returns TRUE if node has two children */
int has_2_ch(Node* node)
{
return (node->left != NULL && node->right != NULL);
}
This is the complete java code for your question.
import java.util.ArrayList;
import java.util.Scanner;
/*
* Creating datastructure for Node
* Every Node contains data given by user and leftChild and rightChild childs
* Left and rightChild childs are automatically assigned by the program
*/
class Node
{
Node leftChild, rightChild;
String data;
/*
* Assigning leftChild , rightChild and data to the node using a constructor
*/
Node(Node left, Node right, String data)
{
this.leftChild =left;
this.rightChild =right;
this.data=data;
}
}
public class FirstAnswer {
/*
* Initializing the count for number of nodes
*/
private static int count=0;
private static int numberOfNodes(Node root)
{
/*
* Writing the base case for the recursive function
* If leftChild or rightChild or both are null it returns 0 as no childs are present
*/
if ((root.leftChild ==null && root.rightChild ==null) || (root.leftChild ==null) || (root.rightChild ==null))
return 0;
else {
count+=2;
Node left=root.leftChild;
Node right=root.rightChild;
/*
* Calling the recursive function twice by making leftChild child and rightChild child of root as root
*/
System.out.println(root.data+" : "+"\n"+"Left child : "+left.data+"\n"+"Right child : "+right.data);
numberOfNodes(left);
numberOfNodes(right);
}
return count+1; //Since root node is not counted
}
public static void main(String... args)
{
Scanner sc=new Scanner(System.in);
/*
* Creating individual nodes with string data from user
* Holding them in an array list inputs
*/
ArrayList<Node> inputs=new ArrayList<>();
String status="Y";
System.out.print("Enter data for root node : ");
inputs.add(new Node(null,null,sc.next()));
while (status.equals("Y") || status.equals("y"))
{
if (inputs.size()%2==1)
{
for (int j=0;j<2;j++)
{
System.out.print("data for child "+(j+1)+" : ");
inputs.add(new Node(null,null,sc.next()));
}
/*
* Yes or No for adding more number of nodes
*/
System.out.println("Press Y or y if more inputs have to be given else press N to construct tree with given inputs...");
status=sc.next();
}
}
Node[] tree=new Node[inputs.size()];
/*
* Above is the tree which is being constructed from the nodes given by user
*/
for (int i=inputs.size()-1;i>=0;i--)
{
int j=i+1;
/*
* Making tree format by locating childs with indices at 2*p and 2*p+1
*/
if ((2*j+1)<=inputs.size())
{
tree[i]=new Node(tree[2*i+1],tree[2*i+2],inputs.get(i).data);
}
else {
tree[i]=inputs.get(i);
}
}
/*
* Calling the recursive function to count number of nodes
* Since first node is the root we start from here
*/
System.out.println(numberOfNodes(tree[0]));
}
}
Hope this helps you ;)

Insertion in BST

I was doing a problem on insertion. This is the right answer.
/*
Node is defined as
typedef struct node
{
int data;
node * left;
node * right;
}node;
*/
node * insert(node * root, int value)
{
if(root == NULL)
{
node *temp = new node();
temp->left = NULL;
temp->right = NULL;
temp->data = value;
root = temp;
return root;
}
if(value > root->data)
{
root->right = insert(root->right, value);
}
else
root->left = insert(root->left, value);
return root;
}
The only difference with the solution I made is that in the if/else statements I did not assign anything. This is my code.
Node is defined as
typedef struct node
{
int data;
node * left;
node * right;
}node;
*/
node * insert(node * root, int value)
{
if(root == NULL)
{
node *temp = new node();
temp->left = NULL;
temp->right = NULL;
temp->data = value;
root = temp;
return root;
}
if(value > root->data)
{
insert(root->right, value);
}
else
insert(root->left, value);
return root;
}
I am not sure I understand why this is necessary because basically calling this function recursively will find a right place for the node with the data value.
Then, I create node with right data and just insert it there.
I will leave a link to the problem. https://www.hackerrank.com/challenges/binary-search-tree-insertion
Thanks for help!

Lowest Common Ancestor of a Binary Search Tree code doesn't pass

can anyone help me with this code? I cannot figure out where I'm blocked.
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
TreeNode* res=NULL;
int i=0;
postTrav(root,p,q,res,i);
return res;
}
void postTrav(TreeNode* root, TreeNode* p, TreeNode* q,TreeNode* res,int& i){
if(!root){
return;
}
postTrav(root->left,p,q,res,i);
postTrav(root->right,p,q,res,i);
if(root==p||root==q){
i++;
}
if(i==2){
res=root;
i++;
}
}
You may have a logic bug in addition to this, but, because C [I assume] is call-by-value, setting res and i are changed local to a given function invocation, but then discarded. You'll need to pass around some addresses, as below. Especially, note that res is now TreeNode ** in postTrav.
TreeNode *
lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
{
TreeNode *res = NULL;
int i = 0;
postTrav(root, p, q, &res, &i);
return res;
}
void
postTrav(TreeNode *root, TreeNode *p, TreeNode *q, TreeNode **res, int *i)
{
if (!root) {
return;
}
postTrav(root->left, p, q, res, i);
postTrav(root->right, p, q, res, i);
if (root == p || root == q) {
*i++;
}
if (*i == 2) {
*res = root;
*i++;
}
}
UPDATE:
The above code is fine. But, whenever, I have a function that needs to return or maintain two or more values [in parallel], a technique I use is to create an additional "traversal" or "helper" struct that simplifies the argument passing.
If you needed an additional variable that needed to be modified/maintained across the calls, instead of adding an additional argument to all functions, it becomes easy/easier to just add another variable to the struct. This works particularly well when you're building up your logic as you go along.
Here's the code for the refinement. Notice that fewer arguments need to be pushed/popped. And, this probably executes as fast or faster than the original. Also, for me, trav->res seems a bit cleaner than *res
// traversal "helper" struct
struct _traverse {
TreeNode *p; // not modified
TreeNode *q; // not modified
TreeNode *res; // result
int i; // depth
// add more variables here as desired ...
#ifdef WANT_TRAVERSAL_STATISTICS
int visited_count; // number of nodes we visited
#endif
};
typedef struct _traverse Traverse;
TreeNode *
lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
{
Traverse trav;
trav.p = p;
trav.q = q;
trav.res = NULL;
trav.i = 0;
#ifdef WANT_TRAVERSAL_STATISTICS
trav.visited_count = 0;
#endif
postTrav(root, &trav);
#ifdef WANT_TRAVERSAL_STATISTICS
printf("Visited %d Nodes\n",trav.visited_count);
#endif
return trav.res;
}
void
postTrav(TreeNode *root, Traverse *trav)
{
if (!root) {
return;
}
#ifdef WANT_TRAVERSAL_STATISTICS
trav->visited_count += 1;
#endif
postTrav(root->left, trav);
postTrav(root->right, trav);
if (root == trav->p || root == trav->q) {
trav->i++;
}
if (trav->i == 2) {
trav->res = root;
trav->i++;
}
}
You are not using the property of BST. postTrav should be like this:
TreeNode* postTrav(TreeNode* root, TreeNode* p, TreeNode* q,)
{
if (root == NULL||p==NULL||q==NULL) return NULL;
int n1=p->data;
int n2=q->data;
while (root != NULL)
{
// If both n1 and n2 are smaller than root, then LCA lies in left
if (root->data > n1 && root->data > n2)
root = root->left;
// If both n1 and n2 are greater than root, then LCA lies in right
else if (root->data < n1 && root->data < n2)
root = root->right;
else break;
}
return root;
}

AVL Tree. Print element by position (when sorted)

#include<stdio.h>
#include<stdlib.h>
// An AVL tree node
struct node
{
int key;
struct node *left;
struct node *right;
int height;
};
// A utility function to get maximum of two integers
int max(int a, int b);
// A utility function to get height of the tree
int height(struct node *N)
{
if (N == NULL)
return 0;
return N->height;
}
// A utility function to get maximum of two integers
int max(int a, int b)
{
return (a > b)? a : b;
}
/* Helper function that allocates a new node with the given key and
NULL left and right pointers. */
struct node* newNode(int key)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1; // new node is initially added at leaf
return(node);
}
// A utility function to right rotate subtree rooted with y
// See the diagram given above.
struct node *rightRotate(struct node *y)
{
struct node *x = y->left;
struct node *T2 = x->right;
// Perform rotation
x->right = y;
y->left = T2;
// Update heights
y->height = max(height(y->left), height(y->right))+1;
x->height = max(height(x->left), height(x->right))+1;
// Return new root
return x;
}
// A utility function to left rotate subtree rooted with x
// See the diagram given above.
struct node *leftRotate(struct node *x)
{
struct node *y = x->right;
struct node *T2 = y->left;
// Perform rotation
y->left = x;
x->right = T2;
// Update heights
x->height = max(height(x->left), height(x->right))+1;
y->height = max(height(y->left), height(y->right))+1;
// Return new root
return y;
}
// Get Balance factor of node N
int getBalance(struct node *N)
{
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
struct node* insert(struct node* node, int key)
{
/* 1. Perform the normal BST rotation */
if (node == NULL)
return(newNode(key));
if (key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);
/* 2. Update height of this ancestor node */
node->height = max(height(node->left), height(node->right)) + 1;
/* 3. Get the balance factor of this ancestor node to check whether
this node became unbalanced */
int balance = getBalance(node);
// If this node becomes unbalanced, then there are 4 cases
// Left Left Case
if (balance > 1 && key < node->left->key)
return rightRotate(node);
// Right Right Case
if (balance < -1 && key > node->right->key)
return leftRotate(node);
// Left Right Case
if (balance > 1 && key > node->left->key)
{
node->left = leftRotate(node->left);
return rightRotate(node);
}
// Right Left Case
if (balance < -1 && key < node->right->key)
{
node->right = rightRotate(node->right);
return leftRotate(node);
}
/* return the (unchanged) node pointer */
return node;
}
/* Given a non-empty binary search tree, return the node with minimum
key value found in that tree. Note that the entire tree does not
need to be searched. */
struct node * minValueNode(struct node* node)
{
struct node* current = node;
/* loop down to find the leftmost leaf */
while (current->left != NULL)
current = current->left;
return current;
}
struct node* deleteNode(struct node* root, int key)
{
// STEP 1: PERFORM STANDARD BST DELETE
if (root == NULL)
return root;
// If the key to be deleted is smaller than the root's key,
// then it lies in left subtree
if ( key < root->key )
root->left = deleteNode(root->left, key);
// If the key to be deleted is greater than the root's key,
// then it lies in right subtree
else if( key > root->key )
root->right = deleteNode(root->right, key);
// if key is same as root's key, then This is the node
// to be deleted
else
{
// node with only one child or no child
if( (root->left == NULL) || (root->right == NULL) )
{
struct node *temp = root->left ? root->left : root->right;
// No child case
if(temp == NULL)
{
temp = root;
root = NULL;
}
else // One child case
*root = *temp; // Copy the contents of the non-empty child
free(temp);
}
else
{
// node with two children: Get the inorder successor (smallest
// in the right subtree)
struct node* temp = minValueNode(root->right);
// Copy the inorder successor's data to this node
root->key = temp->key;
// Delete the inorder successor
root->right = deleteNode(root->right, temp->key);
}
}
// If the tree had only one node then return
if (root == NULL)
return root;
// STEP 2: UPDATE HEIGHT OF THE CURRENT NODE
root->height = max(height(root->left), height(root->right)) + 1;
// STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to check whether
// this node became unbalanced)
int balance = getBalance(root);
// If this node becomes unbalanced, then there are 4 cases
// Left Left Case
if (balance > 1 && getBalance(root->left) >= 0)
return rightRotate(root);
// Left Right Case
if (balance > 1 && getBalance(root->left) < 0)
{
root->left = leftRotate(root->left);
return rightRotate(root);
}
// Right Right Case
if (balance < -1 && getBalance(root->right) <= 0)
return leftRotate(root);
// Right Left Case
if (balance < -1 && getBalance(root->right) > 0)
{
root->right = rightRotate(root->right);
return leftRotate(root);
}
return root;
}
// A utility function to print preorder traversal of the tree.
// The function also prints height of every node
void preOrder(struct node *root)
{
if(root != NULL)
{
preOrder(root->left);
printf("%d ", root->key);
preOrder(root->right);
}
}
/* Drier program to test above function*/
int main()
{
struct node *root = NULL;
/* Constructing tree given in the above figure */
root = insert(root, 9);
root = insert(root, 5);
root = insert(root, 10);
root = insert(root, 0);
root = insert(root, 6);
root = insert(root, 11);
root = insert(root, -1);
root = insert(root, 1);
root = insert(root, 2);
root = insert(root, 10);
printf("Pre order traversal of the constructed AVL tree is \n");
preOrder(root);
root = deleteNode(root, 10);
printf("\nPre order traversal after deletion of 10 \n");
preOrder(root);
return 0;
}
How can i print an element when I give a certain position?
example:
root = insert(root, 100); (add 100)
root = insert(root, 300); (add 300)
root = insert(root, 200); (add 200)
root = insert(root, 200); (add 400)
PRINT 1 -> Should print the first element (sorted). Which is 100
PRINT 3 -> Should print the third element (sorted). Which is 300
How can I implement this PRINT on my AVL Tree?
I tried to modify this function but i did not succeed
void preOrder(struct node *root)
{
if(root != NULL)
{
preOrder(root->left);
printf("%d ", root->key);
preOrder(root->right);
}
}
I couldn't use a if statment here to check what values are passing because they are all passed at the same time.
preOrder function will order the numbers. lower to biggest.
I don't understand why you can't modify preOrder to do that - you just have to "remember" that current position an update it along the way:
int findPositionPreOrder(
struct node *root,
int targetPos,
int curPos)
{
if(root != NULL)
{
int newPos = findPositionPreOrder(root->left, targetPos, curPos);
newPos++;
if (newPos == targetPos)
{
printf("%d\n", root->key);
}
return findPositionPreOrder(root->right, targetPos, newPos);
}
else
{
return curPos;
}
}
And you call it like findPositionPreOrder(root, targetPosition, 0);
This is not an optimal solution - you can break the recursion after finding your desired position instead of traversing the rest of the tree.

Resources