find sum of maximum possible triangular chord - c++

I am having a binary tree
2
/ \
3 4
/ \ \
5 1 8
/ \ / \
1 6 9 2
\
4
i want to find the maximum possible triangular chord info sum of nodes ( between any two leaves and a node having both left and right child ) in the given tree.
a triangular chord will be
for triangular chord :
just imagine a line between any two leaves, go upward towards root, find a common parent (that can be parent, grandparent, grandgrandparent or even the root itself). While moving upwards, for each leaf ( for any leaf either we have to go upward only left left left .... and so OR either only right right right right .. and so) means ( left leaf will only move right upward only and right leaf will move left upward only..... So for any single leaf, we can not move in both direction while moving upwards).. Now we get a triangular shape.. in which a side may contain any no. of nodes/links possible.. NOW, if that triangular shape does not contain any extra internal branches. that triangular shape will be a triangular chord.
Do remember that every leaf node is also always a triangular chord (It is just to create the default cases if the binary tree do not have any triangular shaped chord)
now
maximum triangular chord will be that triangular chord
which have maximum total in sum of all its node info.
we are required to return that maximum total.
If we do not have triangular shaped chord..
then we have to return the leaf with maximum info.
for example
8
/ \
2 3
\
3
is a triangular chord
8
/ \
2 3
\ \
4 1
only subtree with single node 4 will be maximum triangular chord (as its sum is greater than another triangular chord with single node 1) Not the whole tree will be triangular chord
8
/ \
2 3
/ \
4 3
is a triangular chord
so the solution of the very first tree on the first line of question is
8+9+2+4 = 23
i am badly trapped in this problem.
I have a rough approach
I will recursively call leftchild as root of subtree and find the left maximum triangular chord sum
then same for rightchild as root of subtree.
add the max of leftmax and rightmax, and the add to rood node and return
in c++ mycode is :
int maxtri(node* n)
{
if(n)
{
lsum = maxtri(n->left);
rsum = maxtri(n->right);
k = maxof(lsum,rsum);
return (n->info + k);
}
}
edit : my another recursive approach
int l =0, r =0;
int maxtri(node* n)
{
if (n == NULL) return 0;
if (!(n->left) && !(n->right)) return n->info;
if ((n->left) && (n->right))
{
l = maxtri(n->left);
r = maxtri(n->right);
}
if ((n->left) && !(n->right))
{
l = l + maxtri(n->left);
}
if (!(n->left) && (n->right))
{
r = r + maxtri(n->right);
}
return (l+r+n->info);
}
i have doubt on my approach.
can anyone give another solution.??

What about this logic:
For each node traverse the left portion and right portion, if you find any branches then don't consider this node in your calculation else consider this. Moreover, for the part of calculation node should have left & right nodes or it should be leaf node.
Note: I have not tested it properly but i believe it should work.
// Node by Node traverse the tree
void addSum(Node *head, vector<int>& sum)
{
if (head == NULL)
return;
else {
int s = traverseThisNode(head);
sum.push_back(s); // Add to vector
addSum(head->left, sum);
addSum(head->right, sum);
}
}
// For each node traverse left & right
int traverseThisNode(Node *head)
{
if (head && head->left && head->right) {
Node *temp = head; // To traverse right portion of this node
int sum = head->value;
while(head->left) { // Traverse right
head = head->left;
sum = sum + head->value;
if (head->right) { // Condition to check if there is any branching
sum = 0;
break;
}
}
while(temp->right && sum != 0) { // Traverse Right now
temp = temp->right;
sum = sum + temp->value;
if (temp->left) { // Condition to check if there is any branching
sum = 0;
break;
}
}
return sum;
} else if (head && !head->left && !head->right) {
return head->value; // To add leaf node
}
return 0;
}
Now you have vector containing all the value of triangular in the tree, traverse it and
find the maximum.
int maximum()
{
// Traverse the vector "sum" & find the maximum
}

I write the pseudocode for my approach, as far as I have understood the question.
Max = min_value; //possibly 0 if no negative value is allowed for nodes.
sum = 0;
for each node in the tree
temp = node;
sum+= temp->data //collects data at the current level, the current level may be leaf too.
Until temp->left is not null, // Traversing uni-directionally to the left most deep and collecting data.
temp = temp->left
sum+=temp->data
Until temp->right is not null, // Traversing uni-directionally to the right most deep and collecting data.
temp = temp->right
sum+= temp->data
if(sum > Max)
Max = sum;
sum = 0;
print Max;

Related

How to optimize this graph/tree problem counting distance between two nodes in C++?

Problem is to find sum of distance between two nodes in a tree
INPUT: 6 [[0,1],[0,2],[2,3],[2,4],[2,5]]
shows nodes
OUTPUT: [8,12,6,10,10,10]
Explanation: The tree is shown above.
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
equals 1 + 1 + 2 + 2 + 2 = 8.
Hence, answer[0] = 8, and so on.
This is my code, I have solved it but this gives TLE and unable to optimize this solution
How I can optimize this graph problem.
class Solution {
public:
vector<int> sumOfDistancesInTree(int n, vector<vector<int>>& edges) {
vector<int> g[n];
map<pair<int,int>,int> m;
for(auto i:edges){
g[i[0]].push_back(i[1]);
g[i[1]].push_back(i[0]);
}
for(int i=0;i<n;i++){
queue<int> q;
q.push(i);
vector<bool> vis(n,0);
vis[i]=1;
int incr=1;
while(!q.empty()){
int k=q.size();
while(k--){
int t=q.front();q.pop();
for(int j=0;j<g[t].size();j++){
if(!vis[g[t][j]] && g[t][j]!=i){
m[{i,g[t][j]}]+=incr;
q.push(g[t][j]);
vis[g[t][j]]=1;
}
}
}
incr++;
}
}
vector<int> res(n,0);
for(auto i:m){
res[i.first.first]+=i.second;
}
return res;
}
};
As I can see you are using bfs for every node to find the distance.
What you can do is use dynamic programming
Follow the steps below to solve the problem
Initialize a vector dp to store the sum of the distances from each node i to all the leaf nodes of the tree.
Initialize a vector leaves to store the count of the leaf nodes in the sub-tree of node i considering 1 as the root node.
Find the sum of the distances from node i to all the leaf nodes in
the sub-tree of i considering 1 as the root node using a modified
Depth First Search Algorithm.
Let node a be the parent of node i
leaves[a] += leaves[i] ;
dp[a] += dp[i] + leaves[i]
Use the re-rooting technique to find the distance of the remaining
leaves of the tree that are not in the sub-tree of node i. To
calculate these distances, use another modified Depth First Search
(DFS) algorithm to find and add the sum of the distances of leaf
nodes to node i.
Let a be the parent node and i be the child node, then
Let the number of leaf nodes outside the sub-tree i that are present in the sub-tree a be L
L = leaves[a] – leaves[i] ;
dp[i] += ( dp[a] – dp[i] ) + ( L – leaves[i] ) ;
leaves[i] += L ;

Counting the number of nodes in a level of a binary search tree

Like the title says, I want to count the nodes in for any given level of the tree. I already know how to make member functions for counting all the nodes of the tree, just not sure how to approach a specific level. Here's what I've tried. Any help is appreciated.
First parameter is a point to a character array inputted by the user. root is a private variable representing the "oldest" node.
int TreeType::GetNodesAtLevel(ItemType* itemArray, int level)
{
TreeNode* p = root;
if (itemArray == NULL)
return;
if (level == 0)
{
cout << p->info << " ";
return;
}
else
{
GetNodesAtLevel(itemarray->left, level); //dereference in one and not the other was just testing
GetNodesAtLevel(*itemarray->right, level); //neither seems to work
}
}
The way to do it is by using a queue (employing level order traversal - BFS). Now follow this:
Take two variables, count_level and count_queue (keeping total nodes in a queue).
for a tree like this:
A
/ \
B C
/ \ \
K L D
/
E
initially count_level = 0 and count_queue = 0. Now:
Add a node to the queue(at this point A, increment count_queue to 1).
Now when you find count_level = 0 do this -> count_level = count_queue.
Add the kid nodes while dequeuing till the count_level becomes 0. So at this point the follow step 2 and that will give you the no of nodes at level beneath what just has been processed.

Binary tree insert function does not work over 10 entries

I have a binary tree with nodes like this:
struct node
{
int info;
node *left = NULL;
node *right = NULL;
node();
node(int data, node* ln = 0, node* rn = 0): info(data), left(ln), right(rn) {}
};
bool addItemToTree(struct node* node, int item, bool isRoot) {
if (!node)
return false;
if (isRoot) {
node->info = item;
return true;
}
if (!node->left) {
node->left = new struct node(item);
}
else if (!node->right) {
node->right = new struct node(item);
}
else {
if (node->left->left && node->left->right && (!node->right->left || !node->right->right)) {
return addItemToTree(node->right, item, false);
}
else {
return addItemToTree(node->left, item, false);
}
}
return true;
}
int main()
{
node* root = createRoot();
for (int i = 1; i <= 13; i++) {
if (i == 1) {
addItemToTree(root, i, true);
}
else {
addItemToTree(root, i, false);
}
}
}
For some reason, my insert function (adds element to tree) stops working after 10 iterations, meaning it adds elements into an incorrect node (doesn't follow binary tree pattern). Anyone know why it breaks? Thanks.
I assume it's actually after 11 iterations, not 10.
That's because after 11 iterations your tree looks like this:
1
/ \
2 3
/ \ / \
4 5 6 7
/ \ / \
8 9 10 11
Now you want to add 12 under 6, for that your addItemToTree, when looking at 1, needs to go to the right. But it only goes to the right if the right child has no children of its own. In this case the right child of 1 is 3, and it has children of its own, so your method will go to the left, which is wrong.
To fix it, you will need to maintain some auxiliary information about the nodes that would let you decide when to go to the left and when to the right. Some options:
Store the total number of nodes in a subtree. If the left subtree has number of children that is 1 less that some power of two, and the right child has less than that, go to the right (try to prove why that works).
Store whether a subtree has openings at the current depth. You go to the left child if either left->hasOpenings or if !left->hasOpenings && !right->hasOpenings (the latter means that the tree is full at the current depth, and needs to be extended). You set hasOpenings for a parent of a node whenever you recurse to a left child of the node.
In your addItemToTree maintain the current depth (the depth of the root being 0). Let leftmostOne be the index of the leftmost 1 in the binary representation of item. Go to the left if item & (1 << (leftmostOne - depth - 1)) == 0. E.g. when you add 9, the leftmostOne is 3. Then you will do three iterations, and make the following decisions:
At node 1, depth 0, 9 & (1 << (3 - 0 - 1)) = 0, go left
At node 2, depth 1, 9 & (1 << (3 - 1 - 1)) = 0, go left
At node 3, depth 2, 9 & (1 << (3 - 2 - 1)) = 1, go right
Which is exactly what you want.
Try to prove why this works for the general case.

Understanding Balance Factors/Node Height for AVL rotations

So I am having a hard time understanding how to balance AVL trees. I understand the rotation stuff, but I can't figure out how to find the balance factor of node heights, for example:
http://i.imgur.com/yh5zNIl.png
Can anyone explain to me how we actually find the balance factor for EACH node?
I know if the height of [(left subtree) - (right subtree)] is not within (-1<= x <= 1) then its unbalanced...but I can't figure how to find "x".
(edit: I don't need code, I just want to understand how to find BF).
If I understand your question correctly, you want to know how to maintain the balance-factor of a given node. The best way to keep the track is when doing an "insert" in the tree. This is because you know whether your new node is going to the left or the right side of the "current" node. When it goes to the left, you decrement the balance and when it goes to the right, you increment the balance. The idea is to have the tree already balanced before you exit the "insert" method.
Another approach I have seen is NOT doing the balancing during the "insert". You simply insert like you would in BST. After the insert, you begin your balancing act where you get the left subtree and right subtree height at each node and start shuffling pointers. This is not a good approach since you incur O(logn) for every node in finding the height and since you would do that for every node, it results into n*O(logn).
I am posting the "insert" method that I once wrote that keeps the tree balanced at every insert and does NOT compute the height separately at any point during the insert. See if it helps:
Node*
AVL::insert(Node* node, int key, int value)
{
if(node == NULL)
node = new Node(key, value);
else if (key <= node->key)
{
node->balance--;
node->left = insert(node->left, key, value);
}
else if (key > node->key)
{
node->balance++;
node->right = insert(node->right, key, value);
}
// Right Tree Heavy
if (node->balance == 2)
{
// Left tree unbalanced
if (node->right && node->right->balance == 1)
{
// LL
node = singleLeftRotation(node);
node->balance = 0;
node->left->balance = 0;
}
if (node->right && node->right->balance == -1)
{
// LR
int nodeRLBalance = node->right->left->balance;
node = doubleLeftRotation(node);
node->balance = 0;
node->left->balance = nodeRLBalance == 1 ? -1 : 0;
node->right->balance = nodeRLBalance == -1 ? 1 : 0;
}
}
// Left Tree Heavy
if (node->balance == -2)
{
// Right tree unbalanced
if (node->left && node->left->balance == -1)
{
// RR
node = singleRightRotation(node);
node->balance = 0;
node->right->balance = 0;
}
if (node->left && node->left->balance == 1)
{
// RL
int nodeLRBalance = node->left->right->balance;
node = doubleRightRotation(node);
node->balance = 0;
node->left->balance = nodeLRBalance == 1 ? -1 : 0;
node->right->balance = nodeLRBalance == -1 ? 1 : 0;
}
}
return node;
}
The balance factor of a node is the difference of the height of it's left and right descendant nodes.
The balance factor is defined by some as:
balance = node.left.height - node.right.height
and by other as:
balance = node.right.height - node.left.height
so if you want to understand the balance of some nodes in a graph you have to know how they define the balance factor.
For example wikipedia defines it as node.left.height - node.right.height
and you can see that the formula results matches the node balance factors
Avl Tree Balance of Nodes Example
X is the height of the left subtree - the height of the right subtree.
If the left subtree has a max height of three and the right subtree has a max height of two, then the balance factor would be
3 - 2 = Balance Factor of 1 (Left Heavy)
The other way around:
2 - 3 = Balance Factor of -1 (Right Heavy)
If both are the same:
3 - 3 = Balance Factor of 0 (Even Heavy)
A tree becomes unbalanced when the difference between the heights is greater than 1 or less than -1.
5 - 3 = Balance Factor of 2 (UNBALANCED!)
3 - 5 = Balance Factor of -2 (UNBALANCED!)
this image will probably help you. Unbalanced AVL tree has a violation in the E-node
unbalanced AVL tree

Finding Diameter of a Tree

I have written code for finding the diameter of binary tree. But I am unable to figure out where is it going wrong . The two functions that I have written and their definition are as follows :-
int btree::diameteroftree(node* leaf)
{
if (leaf==NULL)
return 0;
int lheight = hieghtoftree(leaf->left);
int rheight = hieghtoftree(leaf->right);
int ldiameter = diameteroftree(leaf->left);
int rdiameter = diameteroftree(leaf->right);
return max(lheight + rheight + 1,max(ldiameter,rdiameter));
}
int btree::hieghtoftree(node* leaf)
{
int left=0,right=0;
if(leaf==NULL)
return -1;
else
{
left=hieghtoftree(leaf->left);
right=hieghtoftree(leaf->right);
if(left > right)
return left +1;
else
return right+1;
}
}
I am unable to figure out where am I going wrong here . Can someone let me know ...
You want to return the number of nodes on the longest path. Therefore, the problem in your algorithm is this line:
return max(lheight + rheight + 1,max(ldiameter,rdiameter));
where
rootDiameter = lheight + rheight + 1
is the length of the path from the deepest node of the left tree to the deepest node of the right tree. However, this calculation is not correct. A single node returns a height of 0, so it will not be counted. You have two options:
Change hieghtoftree to return the number of nodes on the deepest path and not the number of "hops"
Address this problem in your summation
.
return max(lheight + rheight + 3,max(ldiameter,rdiameter));
In a directed, rooted tree, there is always at most one path between any pair of nodes and the longest path to any node always starts at the root. It follows that the diameter is simply the height of the entire tree height(root), which can be computed with the recursion
height(leaf) = 0
height(node) = max(height(node.left), height(node.right)) + 1
EDIT: the page you link to in the comment describes the diameter of an undirected tree. You need a different tree representation, e.g. an adjacency matrix.
Consider a 3-node tree with root R and 2 leaves L1, L2. Then heightoftree(L1) == heightoftree(L2) == -1. Diameteroftree(R) would therefore be (-1)+(-1)+1 = -1 ?!?
I suggest return -1; --> return 0;
and
return max(lheight + rheight + 1,max(ldiameter,rdiameter)); --> return max(lheight + rheight + 2,max(ldiameter,rdiameter));
The result would be the number of edges on the path. If you count the number of nodes, then add one or subtract one from the final result according to your need.