Binary Search Tree Rules - algorithm

Why is this Binary tree considered as an invalid Binary Search Tree:

Binary Tree: In computer science, a binary tree is a tree data structure in which each node has at most two children, which are referred to as the left child and the right child.
Binary Search Tree: In computer science, a binary search tree (BST), also called an ordered or sorted binary tree, is a rooted binary tree data structure whose internal nodes each store a key greater than all the keys in the node’s left subtree and less than those in its right subtree.
Notice that, definition involves the term subtree, not child. I think there is a little confusion in your mind about that.
Correct definiton: store a key greater than all the keys in the node’s left subtree and less than those in its right subtree
Incorrect definition: store a key greater than all the keys in the node’s left child and less than those in its right child.
Why subtree? Well because we want to perform the insert operation in a definite way: If we put 17, 6 and 19 to our binary tree and looking for a node place to insert 22, where should we put it?
If the second definition was true, then where to place 22 would be indefinite. We could have placed it as right child of 9 or right child of 19.
First definition requires us to put it as right child of 19.
References:
Binary Tree
Binary Search Tree

The value 22 is misplaced. The nodes at the left of the root (17) should never be greater than it. This is not only the rule for the immediate child (6), but must be true for all of the left subtree.
Just imagine you would search this tree for value 22 using a binary search: then you would compare 22 with the root's value and decide to look in the right subtree (because it is greater). You would not find it there, and so you would conclude that the tree does not have the value 22.

Related

Does each level in a binary search tree need to be ordered?

I'm reading about binary search trees, and most resources state that binary search trees need to abide by two rules (vs. regular trees):
Each node has a maximum of up to two children.
For each node, the values of its left descendent nodes are less than that of the current node, which in turn is less than the right descendent nodes (if any).
But does that mean we can have a tree where the levels are not in chronological order? For example, I found this image online and wasn't sure if it was a valid binary search tree since the third level from the top is not in order. So if I wanted to search for the number 4 I wouldn't know whether to search for it in the left or right branch.
This is not a binary search tree, as descendent nodes of a node u include all nodes that can be accessed going down a path starting at u.
Here 11 -> 12 -> 4 is a path down from 11, going first through the right child 12, so 4 is a right descendent node of 11. Since its value is smaller, this tree is not a binary search tree.
As a consequence of these rules, all layers are indeed sorted. In fact the whole in-order traversal is sorted.

BST element ordering

In a BST (binary search tree), can any element to the right of the root node be smaller than the root node?
Ie, root is 4, right child is 10, then the left child of that right child is -234
Is it possible/allowed in the definition?
No. See Binary search tree
A binary search tree is a rooted binary tree, whose internal nodes each store a key (and optionally, an associated value) and each have two distinguished sub-trees, commonly denoted left and right. The tree additionally satisfies the binary search property, which states that the key in each node must be greater than or equal to any key stored in the left sub-tree, and less than or equal to any key stored in the right sub-tree.
When you arrive at some, say it contains value 4, and you want to find node with value -234, you always go to the left and if you want to find a node with value 10 you always go to the right.

How to find all elements in an ordered dictionary implemented as a binary tree that have the key k

Given a binary tree I need to implement a method findAllElements(k) to find all the elements in the tree with a key equal to k.
The idea I had is the first time you come across an element with key k. All the elements with the same key should be either in the left child's right subtree or the right child's left subtree. But I was told this may not be the case?
I just need to find a way to implement an algorithm. So pseudo code is needed.
I probably should have added this sorry. But the implementation is that the left subtree contains keys less than or equal to the key at the root and the right subtree contains keys greater than or equal to the key at the root.
It depends on your tree implementation, by binary tree I assume you mean binary search tree, and you use operator< to compare the key. That is, The left subtree of a node contains only nodes with keys less(<) than the node's key, and the right subtree of a node contains only nodes with keys not less(!<) than the node's key.
e.g.
7
/ \
4 7
/ \
6 8
If there is multi equal keys in the tree, do this
k < current_node_key, search left subtree
k > current_node_key, search right subtree
k == current_node_key, record current node , then search right tree
Look at the current node. If its key is higher than k, search the left subtree. If it is lower, search the right subtree. If it is equal, search both left and right subtrees (and also include the current node in the results).
Do that recursively starting from the root node.
Thought I'd come back and explain what the result should have been after conversing with me teacher. So if you perform a method findElement(k) that will find an element with the key equal to k, the element it find should be the element highest in the tree with key k (let's denote this element V).
Then from this element V, other elements the contain a key=k will either be in the left child subtree (particularly all the way to the right) or the right child subtree (particularly all the way to the left). So for the left child keep going to the next nodes right child until an element with key=k is found...now... every element in the subtree with this node as its root must have a key=k (this is the part i didn't recognize at first) thus ANY kind of traversal of this full subtree can be done to find and store all the elements in this subtree (visiting every node in it). This type of thing must be repeated for the right child but visiting every left child until an element with a key=k is found. then the subtree with this element as its root has all the other elements with key=k in it and they can be found by one again fully traversing this subtree.
That is just a word description of it obviously, sorry for the length, and any confusion. Hopefully this will help anyone else trying to solve a similar problem.

A tree data structure where every left node is greater than every right node in a max situation?

Does such a tree exist and have a name, or is it just a figment of my imagination? I used to think heaps have this property but it just seems that the only requirement is for the children to be less than the parent.
It's exactly the opposite, but you may be thinking of a binary search tree, which has the following properties:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
There must be no duplicate nodes.
So every left node is guaranteed to be less than every right node. You can find the max by going right from the root node until you can't go right any more.

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