Why segment tree needs to be a full binary tree? - algorithm

When constructing a segment tree, why it needs to be a full binary tree? I took some example input arrays and when made them to complete binary tree i am getting the same minimum in a range result. Then why make it a full binary tree when complete binary tree is also giving the same result.
Input array- 1, 3, 5, 7, 9, 11

The array representation of the segment tree for example array 1, 3, 5, 7, 9, 11 can be stored like (assuming the range query is finding the minimum element)
Sorry for a lazy diagram.
The number of tree nodes is calculated as pow*2-1 where pow = smallest power of 2 greater than or equal to n.
Clearly the above segment tree representation is a full binary tree and not a complete binary tree.
Can you share your segment tree array representation how are you storing it as a complete binary tree?

A segment tree is not a complete binary tree. For a binary tree to be complete, all levels except the last one need to be completely filled. Also, for the last level, nodes should be as left as possible.
Considering your input array with 6 elements, the tree will be as follows ( assuming 1-6 indices):-
Clearly, the last level has leaf nodes 1 and 2 followed by missing nodes that could have been children of node 3 (hypothetically) and then leaf nodes 4 and 5. This level has missing nodes with nodes 4 and 5 not as left as possible.
Whereas, every node has either 0 or 2 children making it a full binary tree.

Related

Can the minimum value of a binary search tree not be the leftmost entry?

If I construct a binary search tree as I have below, is it right? Or is such a tree not a valid binary search tree?
7
/ \
5 8
/ \
4 10
Because I have followed the rule of smaller element on the left and larger element on the right. So I imagine this is a binary search tree?
Try to walk the tree manually; pretending that you're a function looking for the 4.
You start at the root of the tree: the 7.
4 is less than 7, so you go left to 5.
4 is less than 5 so you go left again.
There's nothing there, so you'd come to the conclusion that 4 is not in the tree.
Of course that's incorrect though, so no, this is not a valid setup for a BST. It isn't simply that each value needs to only be in the correct position relative to its direct parent. Each value also needs to be in a correct position relative to the other nodes in the tree.
The exact position depends on the insertion order of each value, but with this configuration of values, the 4 should be to the left of the 5.
It's definitely a binary tree, as each node only has two leaves.
But like others said, it's not a binary search tree. A way of judging is for each node, all left leaves' values should be smaller than self's value and all right leaves' values should be greater than self's value. Only in this way can perform binary search.

Printing a binary tree in Prolog based on a matrix

I wanted to print a binary tree by making a matrix based on coordinates which will corresponding nodes have in the tree. The binary tree is balanced and for every node goes that the nodes on the left are less than it and the nodes on the right are greater than it.
My tree is represented by a structure s(L,K,D), where L denotes the left branch N the node, and D the right branch. When it comes to an end the tree finishes with nil. For example, a simple tree with 1 as its first node and 2 and 3 its left and right node, will be represented as s(s(nil,2,nil),1,s(nil,3,nil)).
Binary tree example
In this example, node 7 will have coordinates (3,2). 2 because that is its depth in the binary tree (counting from 0), and 3 because of its index in the monotonically increasing list of nodes of the tree.( the list is [1,2,3,7...]).
Basically I can pack a tree in a matrix of dimensions NxM (N being the number of nodes, and M being the absolute depth of the tree[in this case 3]).
For this example the desired matrix would be:
Matrix example
, where I put ' ' character - where the blanks are, in order for the printing to be achieved in the desired way.
Is there any way to code a function which will generate this matrix?

Ordering binary search trees

When trying to order a set of numbers into a binary search tree, is there always exactly one way to order them so the tree has the shortest height, in other words most efficient?
A set of numbers can be converted to a BST by taking one element as the root of the tree and arranging all other numbers around it. I could see the following situation contradicting this theory:
Picking one root leads to a tree of height h, with the left subtree being 'taller' than the right subtree.
Picking another root leads to a different tree, also of height h, with the right subtree being 'taller' than the left subtree.
Another simple example involves swapping the order of insertion of two consecutive elements that are not directly related, and thus do not affect each other's position in the tree.
Disproof by counter-example.
Let the set S = {0, 1, 2, 3}.
Insert the elements into a binary search tree in the following order: 1, 0, 2, 3
1
/ \
0 2
\
3
Insert the elements into a binary search tree in the following order: 1, 2, 0, 3
1
/ \
0 2
\
3
Because these two trees have different orders of insertion, and yet both have minimum height, the statement that there is only one order of insertion that provides a binary search tree of minimum height is false.
If the actual ordering of elements on the tree is what you're concerned about, insert the elements of the set in the following order: 2, 1, 0, 3
2
/ \
1 3
/
0
Again, this tree has the same height as the previous trees, thus showing that a different ordering of items in the tree can also produce a tree of minimum height.
(An aside)
You can always build a minimum height tree by first sorting the elements of the set, then continually subdividing the sorted set to ensure balance and complete filling of each row.
Take the median element of the set. In the case of an even number of elements, take the larger of the two 'middle' elements. This will become the root of the tree.
Take all the elements below the median. This will become the left subtree of the root.
Take all the elements above the median. This will become the right subtree of the root.
Recursively create the left and right subtrees from these sets.
This should ensure that you have a complete binary tree, which will always be of minimum height.

Find the maximum weight node in a tree if each node is the sum of the weights all the nodes under it.

For exa, this is the tree.
10
12 -1
5 1 1 -2
2 3 10 -9
How to find the node with maximum value?
Given the problem as stated, you need to traverse the entire tree. See proof below.
Traversing the entire tree should be a fairly trivial process.
Proof that we need to traverse the entire tree:
Assume we're able to identify which side of a tree the maximum is on without traversing the entire tree.
Given any tree with the maximum node on the left. Call this maximum x.
Pick one of the leaf nodes on the right. Add 2 children to it: x+1 and -x-1.
Since x+1-x-1 = 0, adding these won't change the sum at the leaf we added it to, thus nor the sums at any other nodes in the tree.
Since this can be added to any leaf in the tree, and it doesn't affect the sums, we'd need to traverse the entire tree to find out if this occurs anywhere.
Thus our assumption that we can identify which side of a tree the maximum is on without traversing the entire tree is incorrect.
Thus we need to traverse the entire tree.
In the general case, you need to traverse the entire tree. If the values in the tree are not constrained (e.g. all non-negative, but in your example there are negative values), then the value in a node tells you nothing about the individual values below it.

Difference between binary tree and binary search tree

Can anyone please explain the difference between binary tree and binary search tree with an example?
Binary tree: Tree where each node has up to two leaves
1
/ \
2 3
Binary search tree: Used for searching. A binary tree where the left child contains only nodes with values less than the parent node, and where the right child only contains nodes with values greater than or equal to the parent.
2
/ \
1 3
Binary Tree is a specialized form of tree with two child (left child and right Child).
It is simply representation of data in Tree structure
Binary Search Tree (BST) is a special type of Binary Tree that follows following condition:
left child node is smaller than its parent Node
right child node is greater than its parent Node
A binary tree is made of nodes, where each node contains a "left" pointer, a "right" pointer, and a data element. The "root" pointer points to the topmost node in the tree. The left and right pointers recursively point to smaller "subtrees" on either side. A null pointer represents a binary tree with no elements -- the empty tree. The formal recursive definition is: a binary tree is either empty (represented by a null pointer), or is made of a single node, where the left and right pointers (recursive definition ahead) each point to a binary tree.
A binary search tree (BST) or "ordered binary tree" is a type of binary tree where the nodes are arranged in order: for each node, all elements in its left subtree are less to the node (<), and all the elements in its right subtree are greater than the node (>).
5
/ \
3 6
/ \ \
1 4 9
The tree shown above is a binary search tree -- the "root" node is a 5, and its left subtree nodes (1, 3, 4) are < 5, and its right subtree nodes (6, 9) are > 5. Recursively, each of the subtrees must also obey the binary search tree constraint: in the (1, 3, 4) subtree, the 3 is the root, the 1 < 3 and 4 > 3.
Watch out for the exact wording in the problems -- a "binary search tree" is different from a "binary tree".
As everybody above has explained about the difference between binary tree and binary search tree, i am just adding how to test whether the given binary tree is binary search tree.
boolean b = new Sample().isBinarySearchTree(n1, Integer.MIN_VALUE, Integer.MAX_VALUE);
.......
.......
.......
public boolean isBinarySearchTree(TreeNode node, int min, int max)
{
if(node == null)
{
return true;
}
boolean left = isBinarySearchTree(node.getLeft(), min, node.getValue());
boolean right = isBinarySearchTree(node.getRight(), node.getValue(), max);
return left && right && (node.getValue()<max) && (node.getValue()>=min);
}
Hope it will help you. Sorry if i am diverting from the topic as i felt it's worth mentioning this here.
Binary Tree stands for a data structure which is made up of nodes that can only have two children references.
Binary Search Tree (BST) on the other hand, is a special form of Binary Tree data structure where each node has a comparable value, and smaller valued children attached to left and larger valued children attached to the right.
Thus, all BST's are Binary Tree however only some Binary Tree's may be also BST. Notify that BST is a subset of Binary Tree.
So, Binary Tree is more of a general data-structure than Binary Search Tree. And also you have to notify that Binary Search Tree is a sorted tree whereas there is no such set of rules for generic Binary Tree.
Binary Tree
A Binary Tree which is not a BST;
5
/ \
/ \
9 2
/ \ / \
15 17 19 21
Binary Search Tree (sorted Tree)
A Binary Search Tree which is also a Binary Tree;
50
/ \
/ \
25 75
/ \ / \
20 30 70 80
Binary Search Tree Node property
Also notify that for any parent node in the BST;
All the left nodes have smaller value than the value of the parent node. In the upper example, the nodes with values { 20, 25, 30 } which are all located on the left (left descendants) of 50, are smaller than 50.
All the right nodes have greater value than the value of the parent node. In the upper example, the nodes with values { 70, 75, 80 } which are all located on the right (right descendants) of 50, are greater than 50.
There is no such a rule for Binary Tree Node. The only rule for Binary Tree Node is having two childrens so it self-explains itself that why called binary.
A binary search tree is a special kind of binary tree which exhibits the following property: for any node n, every descendant node's value in the left subtree of n is less than the value of n, and every descendant node's value in the right subtree is greater than the value of n.
Binary tree
Binary tree can be anything which has 2 child and 1 parent. It can be implemented as linked list or array, or with your custom API. Once you start to add more specific rules into it, it becomes more specialized tree. Most common known implementation is that, add smaller nodes on left and larger ones on right.
For example, a labeled binary tree of size 9 and height 3, with a root node whose value is 2. Tree is unbalanced and not sorted.
https://en.wikipedia.org/wiki/Binary_tree
For example, in the tree on the left, A has the 6 children {B,C,D,E,F,G}. It can be converted into the binary tree on the right.
Binary Search
Binary Search is technique/algorithm which is used to find specific item on node chain. Binary search works on sorted arrays.
Binary search compares the target value to the middle element of the array; if they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is successful or the remaining half is empty. https://en.wikipedia.org/wiki/Binary_search_algorithm
A tree representing binary search. The array being searched here is [20, 30, 40, 50, 90, 100], and the target value is 40.
Binary search tree
This is one of the implementations of binary tree. This is specialized for searching.
Binary search tree and B-tree data structures are based on binary search.
Binary search trees (BST), sometimes called ordered or sorted binary trees, are a particular type of container: data structures that store "items" (such as numbers, names etc.) in memory. https://en.wikipedia.org/wiki/Binary_search_tree
A binary search tree of size 9 and depth 3, with 8 at the root. The leaves are not drawn.
And finally great schema for performance comparison of well-known data-structures and algorithms applied:
Image taken from Algorithms (4th Edition)
Binary search tree: when inorder traversal is made on binary tree, you get sorted values of inserted items
Binary tree: no sorted order is found in any kind of traversal
A binary tree is a tree whose children are never more than two. A binary search tree follows the invariant that the left child should have a smaller value than the root node's key, while the right child should have a greater value than the root node's key.
To check wheather or not a given Binary Tree is Binary Search Tree here's is an Alternative Approach .
Traverse Tree In Inorder Fashion (i.e. Left Child --> Parent --> Right Child ) ,
Store Traversed Node Data in a temporary Variable lets say temp , just before storing into temp , Check wheather current Node's data is higher then previous one or not .
Then just break it out , Tree is not Binary Search Tree else traverse untill end.
Below is an example with Java:
public static boolean isBinarySearchTree(Tree root)
{
if(root==null)
return false;
isBinarySearchTree(root.left);
if(tree.data<temp)
return false;
else
temp=tree.data;
isBinarySearchTree(root.right);
return true;
}
Maintain temp variable outside
A tree can be called as a binary tree if and only if the maximum number of children of any of the nodes is two.
A tree can be called as a binary search tree if and only if the maximum number of children of any of the nodes is two and the left child is always smaller than the right child.
In a Binary search tree, all the nodes are arranged in a specific order - nodes to the left of a root node have a smaller value than its root, and all the nodes to the right of a node have values greater than the value of the root.
In a binary tree, each node has 2 child nodes the left node and the right node.
A Binary Search tree is a special kind of tree in which the nodes are sorted, the left node is smaller than the parent node and the left node is bigger than the parent node.
The binary tree allows duplicate values, Binary search tree doesn't allow duplicate values also carrying out any kind of operation is faster in Binary search tree than in Binary tree since BST is sorted
A binary tree is a tree, in which each node can have at most 2 children.
A binary search tree is a further modification of this, giving a certain relationship to the parent and the two children. Since, there are only two children, i.e., left and right child; the relation is defined as follows:
Left Child <= Parent <= Right Child
It is actually, that simple.

Resources