How to represent a non binary tree and how to do LCA on that tree? - algorithm

How are non binary trees typically represented? Trees where there is no limit to the number of children a node can have. Is it best to use a Adjacency Matrix or Adjacency List and just assume there will be no cycles, or do something similar to this question ->
How to implement a Non-Binary tree
and follow up question, when you have a n-ary tree (is that the correct name for them?) What's a good way to find the Least Common Ancestor for two given nodes/data values in that tree? All I can find are algorithms that deal with binary trees, like this one ->
static Node lca(Node root,int v1,int v2)
{
if (root == null || root.data == v1 || root.data == v2) {
return root;
}
Node left = lca(root.left, v1, v2);
Node right = lca(root.right, v1, v2);
if (left != null && right != null) {
return root;
}
return (left != null) ? left : right;
}

Adjacency matrix sounds like a bad idea, it will be very sparse (most cells will be empty). Usually for n-ary trees (yes that's how they are called) you just follow the same strategy as with the binary tree, the difference is that a binary tree would have 2 fields representing the left and right children:
class Node<T> {
T value;
Node<T> left;
Node<T> right;
}
Here you change those fields into a data structure like an array (static or dynamic):
class Node<T> {
T value;
List<Node<T>> children;
}
As for the LCA, are you planning on storing the parent pointer in the nodes? Are the values supposed to be a tree with unique values? Will the values be ordered in any way?
If no, but you can assume that the nodes are in the tree (although handling the other case is not that hard) then the LCA is very similar to what you've shown above. You just need to change the part where you get the Node left and Node right so that it traverses all children:
int count = 0;
Node<T> temp = null;
for(Node<T> child : root.children) {
Node<T> result = lca(child, v1, v2);
if(result != null) {
count++;
temp = result;
}
}
if(count == 2) {
return root;
}
return temp;
With parent pointers and/or storing the dept in each node we can do better but at a storage cost.

Related

Balanced tree with constant-time successor and predecessor given node pointers?

I was asked this question, which I personally find hard:
Create a data structure that can:
Insert elements,
Remove elements,
Search Elements,
In time O(log n)
In addition,
It should have the following two functions which work in time O(1):
next(x):
given a pointer to the node of value x, return a pointer to the node with the smallest bigger value than x.
previous(x)
given a pointer to the node of value x, return a pointer to the node with the biggest smallest value than x.
If each node contains a pointer to its successor and a pointer to its predecessor, or equivalently - if you maintain both a doublely linked list and a tree, where each node in the tree points to its equivalent node in the list and vice versa - you'll get want you want. Updating the list on insert/delete is O(1) (after locating the closest node in the tree). Searching is performed on the tree. Succesor / predecessor are performed on the list.
#RogerLindsjö's idea from the comments is a good one. Essentially, keep a regular, balanced BST, then thread a doubly-linked list through the nodes keeping them in sorted order. That way, given a pointer to a node in the tree, you can find the largest value smaller than it or the smallest value greater than it simply by following the next or previous pointers in each node.
You can maintain this list through insertions and deletions without changing the overall runtime of an insert or delete. For example, here's how you might do an insertion of an element x:
Do a standard BST successor query to find the smallest value larger than x in the tree, and a standard BST predecessor query to find the largest value smaller than x in the tree. Each search takes time O(log n) to complete.
Do a regular BST insertion to insert x. Then, set its next and previous pointers to the two elements you found in the previous step, and update those nodes to point to your new node x. This also takes time O(log n).
The total time for the insertion is then O(log n), matching what a balanced tree can provide.
I'll leave it to you to figure out deletion, which can similarly maintain the linked list pointers without changing the overall cost of the operation.
Like most self-balancing trees, a B+ tree provides Insert, Remove, and Search operations with O(log n) time complexity.
In a B+ tree, a leaf node hosts multiple keys in an array, so the concept of "pointer to node with value x" does not really exist, but we could define it as the tuple (pointer, index), where the pointer is to the node, and index is the slot in which x is stored.
In a B+ tree the nodes at the bottom level contain all the keys, and these nodes are often linked, usually only in forward direction (i.e. to the right), but it is quite possible to also maintain a link in the opposite direction, without increasing the time complexity of the above operations.
With those two remarks in mind, prev-next operations can clearly be executed in O(1) time.
If your elements are integers you can use y-fast trie that supports all mentioned operations in O(log log m). Also, almost any search tree will allow doing these operations in O(log n) time by just going first up and then down (it will require a lot of concentration to not mess up with the order, though)
You can use two pointers in the node of the balanced tree, namely pred - predecessor and succ - successor. While inserting a node into the tree or deleting a node from the tree you just have to do some pointer manipulations, equivalent to those in doubly linked list.
The time complexity will be O(1) in each case.
I have provided my implementation for the insertion and deletion in case of AVL Tree below. The complete implementation is available here.
Structure of node
template<typename T>
struct node {
T key;
int freq;
node<T> *left;
node<T> *right;
node<T> *pred;
node<T> *succ;
int height;
node(T key): key(key), freq(1),
left(nullptr),
right(nullptr),
height(1),
pred(nullptr),
succ(nullptr) {}
};
insert function
node<T> *insert(node<T> *root, T key) {
if(root == nullptr)
return new node<T>(key);
if(!comp(key, root->key) && !comp(root->key, key)) {
++root->freq;
} else if(comp(key, root->key)) {
if(root->left == nullptr) {
node<T> *new_node = new node<T>(key);
/* set the pred and succ ptrs*/
new_node->succ = root;
new_node->pred = root->pred;
if(root->pred != nullptr)
root->pred->succ = new_node;
root->pred = new_node;
root->left = new_node;
} else {
root->left = insert(root->left, key);
}
} else {
if(root->right == nullptr) {
node<T> *new_node = new node<T>(key);
/* set the pred and succ ptrs*/
new_node->pred = root;
new_node->succ = root->succ;
if(root->succ != nullptr)
root->succ->pred = new_node;
root->succ = new_node;
root->right = new_node;
} else {
root->right = insert(root->right, key);
}
}
root->height = max(height(root->left), height(root->right)) + 1;
int bf = balance_factor(root);
node<T> *left = root->left;
node<T> *right = root->right;
if(bf > 1 && left != nullptr && comp(key, left->key)) {
/*
node was inserted at left subtree of left child
fix - right rotate root
*/
root = rotate_right(root);
} else if(bf > 1 && left != nullptr && comp(left->key, key)) {
/*
node was inserted at right subtree of left child
fix - left rotate left child
- right rotate root
*/
root->left = rotate_left(root->left);
root = rotate_right(root);
} else if(bf < -1 && right != nullptr && comp(right->key, key)) {
/*
node was inserted at right subtree of right child
fix - left rotate root
*/
root = rotate_left(root);
} else if(bf < -1 && right != nullptr && comp(key, right->key)) {
/*
node was inserted at left subtree of right child
fix - right rotate right child
- left roatate root
*/
root->right = rotate_right(root->right);
root = rotate_left(root);
}
return root;
}
erase function
node<T> *erase(node<T> *root, T key) {
if(root == nullptr)
return nullptr;
if(comp(key, root->key)) {
root->left = erase(root->left, key);
} else if(comp(root->key, key)) {
root->right = erase(root->right, key);
} else {
if(root->left == nullptr || root->right == nullptr) {
/* update pred and succ ptrs */
if(root->succ != nullptr)
root->succ->pred = root->pred;
if(root->pred != nullptr)
root->pred->succ = root->succ;
if(root->right == nullptr) {
node<T> *temp = root->left;
delete root;
root = temp;
} else {
node<T> *temp = root->right;
delete root;
root = temp;
}
} else {
// node<T> *succ = minVal(root->right);
root->key = root->succ->key;
root->freq = root->succ->freq;
root->right = erase(root->right, root->succ->key);
}
}
if(root != nullptr) {
root->height = max(height(root->left), height(root->right)) + 1;
int bf_root = balance_factor(root);
if(bf_root > 1) {
/*
case R
*/
int bf_left = balance_factor(root->left);
if(bf_left >= 0) {
/*
case R0 and R1
*/
root = rotate_right(root);
} else {
/*
case R -1
*/
root->left = rotate_left(root->left);
root = rotate_right(root);
}
} else if(bf_root < -1) {
/*
Case L
*/
int bf_right = balance_factor(root->right);
if(bf_right <= 0) {
/*
case L0 and L -1
*/
root = rotate_left(root);
} else {
/*
case L1
*/
root->right = rotate_right(root->right);
root = rotate_left(root);
}
}
}
return root;
}

How to calculate a height of a tree

I am trying to learn DSA and got stuck on one problem.
How to calculate height of a tree. I mean normal tree, not any specific implementation of tree like BT or BST.
I have tried google but seems everyone is talking about Binary tree and nothing is available for normal tree.
Can anyone help me to redirect to some page or articles to calculate height of a tree.
Lets say a typical node in your tree is represented as Java class.
class Node{
Entry entry;
ArrayList<Node> children;
Node(Entry entry, ArrayList<Node> children){
this.entry = entry;
this.children = children;
}
ArrayList<Node> getChildren(){
return children;
}
}
Then a simple Height Function can be -
int getHeight(Node node){
if(node == null){
return 0;
}else if(node.getChildren() == null){
return 1;
} else{
int childrenMaxHeight = 0;
for(Node n : node.getChildren()){
childrenMaxHeight = Math.max(childrenMaxHeight, getHeight(n));
}
return 1 + childrenMaxHeight;
}
}
Then you just need to call this function passing the root of tree as argument. Since it traverse all the node exactly once, the run time is O(n).
1. If height of leaf node is considered as 0 / Or height is measured depending on number of edges in longest path from root to leaf :
int maxHeight(treeNode<int>* root){
if(root == NULL)
return -1; // -1 beacuse since a leaf node is 0 then NULL node should be -1
int h=0;
for(int i=0;i<root->childNodes.size();i++){
temp+=maxHeight(root->childNodes[i]);
if(temp>h){
h=temp;
}
}
return h+1;
}
2. If height of root node is considered 1:
int maxHeight(treeNode<int>* root){
if(root == NULL)
return 0;
int h=0;
for(int i=0;i<root->childNodes.size();i++){
temp+=maxHeight(root->childNodes[i]);
if(temp>h){
h=temp;
}
}
return h+1;
Above Code is based upon following class :
template <typename T>
class treeNode{
public:
T data;
vector<treeNode<T>*> childNodes; // vector for storing pointer to child treenode
creating Tree node
treeNode(T data){
this->data = data;
}
};
In case of 'normal tree' you can recursively calculate the height of tree in similar fashion to a binary tree but here you will have to consider all children at a node instead of just two.
To find a tree height a BFS iteration will work fine.
Edited form Wikipedia:
Breadth-First-Search(Graph, root):
create empty set S
create empty queues Q1, Q2
root.parent = NIL
height = -1
Q1.enqueue(root)
while Q1 is not empty:
height = height + 1
switch Q1 and Q2
while Q2 is not empty:
for each node n that is adjacent to current:
if n is not in S:
add n to S
n.parent = current
Q1.enqueue(n)
You can see that adding another queue allows me to know what level of the tree.
It iterates for each level, and for each mode in that level.
This is a discursion way to do it (opposite of recursive). So you don't have to worry about that too.
Run time is O(|V|+ |E|).

How binary search tree is created?

Suppose i am having an array say
1 5 4 6 8 9 10 22 17 7 9 3
I want to create a binary search tree from this array. I need algorithm to understand that.
I have read rest other things related to BST like inorder traversal preorder postorder, tree walk, insertion deletion etc
Book has not provided how to create BST. Need help here
if you do not care about the tree being balanced it is simple:
put the first element of the tree as the head.
iterate over the array. if an element is bigger than the node take a left(repeat the step for the left child) otherwise take a right(repeat the step for the right child).
if the left/right child is a null insert your new value there.
guaranteed to produce a binary search tree - just not a balanced one.
Firstly, you should choose a root node for your BST. Once you have chosen a root node, it is already easy to construct a BST taking into consideration the fact that: left children are less than the parent node and all right children are greater than the parent node.
private Node root;
public void insert(int val) {
if (root == null) {
root = new Node(val);
} else {
insertHelper(root, val);
}
}
private void insertHelper(Node node, int val) {
if (val < node.val) {
if (node.left == null) {
node.left = new Node(val);
} else {
insertHelper(node.left, val);
}
} else if (node.val < val) {
if (node.right == null) {
node.right = new Node(val);
} else {
insertHelper(node.right, val);
}
}
}
If the given array is sorted, you can do the following:
Take the middle element of the array and make it the root of the tree
Take the left sub-array and make it the left sub-tree of the root recursively
Take the right sub-array and make it the right sub-tree of the root recursively
Otherwise you can always sort the array before applying the procedure
struct node* construct(int arr[], int start, int end)
{
if(start>end)
return;
else if (start==end)
{
/*assuming we have a function newNode(int) which creates a new BST Node*/
node* Node = newNode(arr[start]);
return Node;
}
int mid = (start+end)/2;
node* root = newNode(arr[mid]);
root->left = construct(arr,start,mid-1);
root->right = construct(arr,mid+1,end);
return root;
}

Is Doubly link list OR BST

Given a node with the following structure
class Node {
int data,
Node* P1,
Node* p2;
}
We need to determine, if the node represents a Circular Doubly Link List OR a Binary Tree.
In my opinion We need to start traversing the given node in one direction
node = givenNode;
while(node->P1 != null && node->P1 != givenNode)
{
node = node->p1
}
if(node == givenNode) // It means Circular DLL
else if(node == null) // It means Tree
And it would take O(n) time to detect this.
Please suggest if there is any better approach than this.
I suggest you could check if its a doubl-linked list or not with this piece of code:
node = givenNode;
if(givenNode->P1 == null || givenNode->P2 == null)
// It can not be double link list (circular)
else if(givenNode->p1->p2 == givenNode || givenNode->p2->p1 == givenNode)
{
//It is a double linked list
}
else
{
It is not a double linked list
}
And we have O(1) complexity

How To Find the Mirror Node of a Given Node (or item) in a Binary Tree Efficiently

I've been thinking of this problem, and I have not found a good, efficient solution.
How to find the mirror node of a given node (or item) in a binary tree?
// Node definition
struct _Node {
char data;
struct _Node* left;
struct _Node* right;
} Node;
// Assumption:
// "given" is guaranteed in the binary tree ("root" which is not NULL)
Node* FindMirrorNode(Node* root, Node* given)
{
// Implementation here
}
// OR:
// Assumption:
// in the binary tree ("root"), there is no repeated items, which mean in each node the char data is unique;
// The char "given" is guaranteed in the binary tree.
char FindMirrorNodeData(Node* root, char given)
{
// Implementation here
}
NOTE: I'm NOT asking on how to find a mirror tree of a given tree :-)
For example, considering the tree below
A
/ \
B C
/ / \
D E F
\ / \
G H I
The mirror node of 'D' is node 'F'; while the mirror node of 'G' is NULL.
Thanks.
I've written a solution for the function with the char. Is FindMirrorNode(r, n) == FindMirrorNodeData(r, n->data)?
You have to go through the entire tree searching for the given data while keeping the mirror nodes on the stack. That's a quite simple solution, still quite efficient.
If you want you may transform tail-calls into while.
static Node* FindMirrorNodeRec(char given, Node* left, Node* right)
{
// if either node is NULL then there is no mirror node
if (left == NULL || right == NULL)
return NULL;
// check the current candidates
if (given == left->data)
return right;
if (given == right->data)
return left;
// try recursively
// (first external then internal nodes)
Node* res = FindMirrorNodeRec(given, left->left, right->right);
if (res != NULL)
return res;
return FindMirrorNodeRec(given, left->right, right->left);
}
Node* FindMirrorNodeData(Node* root, char given)
{
if (root == NULL)
return NULL;
if (given == root->data)
return root;
// call the search function
return FindMirrorNodeRec(given, root->left, root->right);
}
Thanks for Chris's beautiful solution. It worked.
Node* FindMirrorNodeRec(Node* given, Node* left, Node* right)
{
// There is no mirror node if either node is NULL
if (!left || !right)
return NULL;
// Check the left and right
if (given == left)
return right;
if (given == right)
return left;
// Try recursively (first external and then internal)
Node* mir = FindMirrorNodeRec(given, left->left, right->right);
if (mir)
return mir;
// Internally
return FindMirrorNodeRec(given, left->right, right->left);
}
// Find the mirror node of the given node
// Assumption: root is not NULL, and the given node is guaranteed
// in the tree (of course, not NULL :-)
Node* FindMirrorNode(Node* const root, Node* const given)
{
if (!root || root == given)
return root;
return FindMirrorNodeRec(given, root->left, root->right);
}

Resources