Posts

Showing posts from May, 2019

What is the difference between the add and offer methods in a Queue in Java?

If a collection refuses to add a particular element for any reason other than that it already contains the element, it  must throw  an exception (rather than returning false). This preserves the invariant that a collection always contains the specified element after this call returns. offer  method - tries to add an element to a queue, and returns  false  if the element can't be added (like in case when a queue is full), or  true  if the element was added, and doesn't throw any specific exception. add  method - tries to add an element to a queue, returns  true  if the element was added, or throws an IllegalStateException if no space is currently available. There is no difference for the implementation of  PriorityQueue.add : public boolean add ( E e ) { return offer ( e ); } For  AbstractQueue  there actually is a difference: public boolean add ( E e ) { if ( offer ( e )) return true ; else throw new IllegalStateE

Tree

Image
What is Tree? A tree is a data structure, each node points to a number of nodes. A tree is an example of non-linear data structures. A tree structure is a way of representing the hierarchical nature of a structure in a graphical form. The root of a tree is the node with no parents. A node with no children is called a leaf node . Children of the same parent are called siblings . A node "p" is an ancestor of node "q" if there exists a path from "root" to "q" and "p" appears on the path. The node "q" is called descendant of p. Set of all node at a given depth is called the level of the tree. The root node is at level zero. The height of the tree is the maximum height among all the nodes in the tree and depth of the tree is the maximum depth among all the nodes in the tree. Binary Tree A tree is called a binary tree if each node has zero child, one child or two children. Types of binary tree Stric