1. 1 http://coursehunt.net/
Data Structures.
1: A Tree Is Typically Traversed In Two Ways:
A) Breadth First Traversal:- This traversal visits nodes by levels from top to bottom and
from left to right.
B) Depth-First Traversal:
There are three different types of depth-first traversals:
PreOrder traversal - visit the parent first and then left and right children.
InOrder traversal - visit the left child, then the parent and the right child.
PostOrder traversal - visit left child, then the right child and then the parent.
Breadth-First Traversal:
This traversal visits nodes by levels from top to bottom and from left to right.
PreOrder - 8, 5, 9, 7, 1, 12, 2, 4, 11, 3
InOrder - 9, 5, 1, 7, 2, 12, 8, 4, 3, 11
PostOrder - 9, 1, 2, 12, 7, 5, 3, 11, 4, 8
LevelOrder - 8, 5, 4, 9, 7, 11, 1, 12, 3, 2
In Below picture, we demonstrate the order of node visitation. Number 1 denotes
the first node in a particular traversal and 7 denote the last node.
2. 2 http://coursehunt.net/
Depth-First Traversal:
There are three different types of depth-first traversals, :
● PreOrder traversal - visit the parent first and then left and right children;
● InOrder traversal - visit the left child, then the parent and the right child;
● PostOrder traversal - visit left child, then the right child and then the parent;
2: Searching Into a Binary Tree:
If we want to search for a node whose key is K, start searching from the root of the binary
search tree.
If the root is NULL, the search contains no nodes and the search is unsuccessful. Otherwise,
compare k with the key in root.
If k equals the root's key, then search is successful. If k is less than root's key, then no
element in the right sub tree can have a key value equal to k, therefore we search the left sub
tree of a root.
If k is larger than root's key value, search the right subtree of the root.
Pseudocode for recursive search of a binary search tree:
element *search(treePointer root, int key) {
if(!root) return NULL;
if(k==root->data.key) return &(root->data);
if(k<root->data.key)
return search(root->leftchild, k);
return search(root->rightchild, k);
}
3. 3 http://coursehunt.net/
3: Inserting into a binary search tree:
● Check whether root node is present or not(tree available or not). If root is NULL,
create root node.
● If the element to be inserted is less than the element present in the root node, traverse
the left sub-tree recursively until we reach T->left/T->right is NULL and place the new node
at T->left(key in new node < key in T)/T->right (key in new node > key in T).
● If the element to be inserted is greater than the element present in root node, traverse
the right sub-tree recursively until we reach T->left/T->right is NULL and place the new
node at T->left/T->right.
Pseudocode:
TreeNode insert(int data, TreeNode T) {
if T is NULL {
T = (TreeNode *)malloc(sizeof (Struct TreeNode));
(Allocate Memory of new node and load the data into it)
T->data = data;
T->left = NULL;
T->right = NULL;
} else if T is less than T->left {
T->left = insert(data, T->left);
(Then node needs to be inserted in left sub-tree.So,
recursively traverse left sub-tree to find the place
where the new node needs to be inserted)
} else if T is greater than T->right {
T->right = insert(data, T->right);
(Then node needs to be inserted in right sub-tree
So, recursively traverse right sub-tree to find the
place where the new node needs to be inserted.)
}
return T;
}
4. 4 http://coursehunt.net/
4: Checking if two binary trees are same:
● Two trees are identical when they have same data and arrangement of data is also same.
Pseudocode:
sameTree(tree1, tree2)
1. If both trees are empty then return 1.
2. Else If both trees are non -empty
(a) Check data of the root nodes (tree1->data == tree2->data)
(b) Check left subtrees recursively i.e., call sameTree(
tree1->left_subtree, tree2->left_subtree)
(c) Check right subtrees recursively i.e., call sameTree(
tree1->right_subtree, tree2->right_subtree)
(d) If a,b and c are true then return 1.
3 Else return 0 (one is empty and other is not)
Time Complexity:
Complexity of the identicalTree() will be according to the tree with lesser number of
nodes. Let number of nodes in two trees be m and n then complexity of sameTree() is O(m)
where m < n
5: Find size of binary tree:
● Start from the root.
● Size = 1 (for the root) + Size Of left Sub-Tree + Size Of right Sub-Tree
● solve the left sub-tree and right sub-tree recursively.
● Size of a tree = Size of left subtree + 1 + Size of right subtree
5. 5 http://coursehunt.net/
6: Find height of binary tree:
● Get the height of left sub tree, say leftHeight
● Get the height of right sub tree, say rightHeight
● Take the Max(leftHeight, rightHeight) and add 1 for the root and return
● Call recursively.
7. 7 http://coursehunt.net/
● Given a binary tree and a number, return true if the tree has a root-to-leaf path such that
adding up all the values along the path equals the given number. Return false if no such path
can be found.
Ex:
in the above tree root to leaf paths exist with following sums.
21 –> 10 – 8 – 3
23 –> 10 – 8 – 5
14 –> 10 – 2 – 2
So the returned value should be true only for numbers 21, 23 and 14. For any other number,
returned value should be false.
Algorithm:
Recursively check if left or right child has path sum equal to ( number – value at current
node)
8: Check if binary tree is a binary search tree:
A binary search tree (BST) is a node based binary tree data structure 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.
From the above properties it naturally follows that:
• Each node (item in the tree) has a distinct key.
Pseudocode:
8. 8 http://coursehunt.net/
/* Returns true if the given tree is a binary search tree
(efficient version). */
int isBST(struct node* node)
{
return(isBSTUtil(node, INT_MIN, INT_MAX));
}
/* Returns true if the given tree is a BST and its
values are >= min and <= max. */
int isBSTUtil(struct node* node, int min, int max)
9: Level order traversal of binary tree:
Level order traversal of the above tree is 1 2 3 4 5
Algorithm:
/*Function to print level order traversal of tree*/
printLevelorder(tree)
for d = 1 to height(tree)
printGivenLevel(tree, d);
/*Function to print all nodes at a given level*/
printGivenLevel(tree, level)
if tree is NULL then return;
if level is 1, then
print(tree->data);
else if level greater than 1, then
printGivenLevel(tree->left, level-1);
printGivenLevel(tree->right, level-1);
METHOD 2 (Use Queue):
For each node, first the node is visited and then it’s child nodes are put in a FIFO queue.
printLevelorder(tree)
1) Create an empty queue q
2) temp_node = root /*start from root*/
3) Loop while temp_node is not NULL
a) print temp_node->data.
b) Enqueue temp_node’s children (first left then right children) to q
c) Dequeue a node from q and assign it’s value to temp_node
9. 9 http://coursehunt.net/
10: Iterative PostOrder traversal of binary tree:
The key to to iterative postorder traversal is the following:
1. The order of "Postorder" is: left child -> right child -> parent node.
2. Find the relation between the previously visited node and the current node
3. Use a stack to track nodes
As we go down the tree to the left, check the previously visited node. If the current node is
the left or right child of the previous node, then keep going down the tree, and add left/right
node to stack when applicable. When there are no children for current node, i.e., the current
node is a leaf, pop it from the stack. Then the previous node become to be under the current
node for next loop
Ex:
1. Push 1 to first stack.
First stack: 1
Second stack: Empty
2. Pop 1 from first stack and push it to second stack.
Push left and right children of 1 to first stack
First stack: 2, 3
Second stack: 1
3. Pop 3 from first stack and push it to second stack.
Push left and right children of 3 to first stack
First stack: 2, 6, 7
Second stack:1, 3
4. Pop 7 from first stack and push it to second stack.
First stack: 2, 6
Second stack:1, 3, 7
5. Pop 6 from first stack and push it to second stack.
First stack: 2
Second stack:1, 3, 7, 6
6. Pop 2 from first stack and push it to second stack.
10. 10 http://coursehunt.net/
Push left and right children of 2 to first stack
First stack: 4, 5
Second stack:1, 3, 7, 6, 2
7. Pop 5 from first stack and push it to second stack.
First stack: 4
Second stack: 1, 3, 7, 6, 2, 5
8. Pop 4 from first stack and push it to second stack.
First stack: Empty
Second stack: 1, 3, 7, 6, 2, 5, 4
The algorithm stops since there is no more item in first stack.
Observe that content of second stack is in postorder fashion. Print them.
11: Iterative Preorder traversal of binary tree:
1. Create a Stack.
2. Print the root and push it to Stack and go left i.e root=root.left and till it hits the NULL.
3. If root is null and Stack is empty Then
1. return, we are done.
4. Else
1. Pop the top Node from the Stack and set it as, root = popped_Node.
2. Go right, root = root.right.
3. Go to step 2.
5. End If
Code:
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
11. 11 http://coursehunt.net/
}
public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> returnList = new ArrayList<Integer>();
if(root == null)
return returnList;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.empty()){
TreeNode n = stack.pop();
returnList.add(n.val);
if(n.right != null){
stack.push(n.right);
}
if(n.left != null){
stack.push(n.left);
}
}
return returnList;
}
}
12: Iterative Inorder traversal of binary tree:
Create an empty stack S.
2) Initialize current node as root
3) Push the current node to S and set current = current->left until current is NULL
4) If current is NULL and stack is not empty then
a) Pop the top item from stack.
b) Print the popped item, set current = popped_item->right
c) Go to step 3.
5) If current is NULL and stack is empty then we are done.
Ex:
1
/
2 3
/
4 5
Step 1 Creates an empty stack: S = NULL
Step 2 sets current as address of root: current -> 1
12. 12 http://coursehunt.net/
Step 3 Pushes the current node and set current = current->left until current is NULL
current -> 1
push 1: Stack S -> 1
current -> 2
push 2: Stack S -> 2, 1
current -> 4
push 4: Stack S -> 4, 2, 1
current = NULL
Step 4 pops from S
a) Pop 4: Stack S -> 2, 1
b) print "4"
c) current = NULL /*right of 4 */ and go to step 3
Since current is NULL step 3 doesn't do anything.
Step 4 pops again.
a) Pop 2: Stack S -> 1
b) print "2"
c) current -> 5/*right of 2 */ and go to step 3
Step 3 pushes 5 to stack and makes current NULL
Stack S -> 5, 1
current = NULL
Step 4 pops from S
a) Pop 5: Stack S -> 1
b) print "5"
c) current = NULL /*right of 5 */ and go to step 3
Since current is NULL step 3 doesn't do anything
Step 4 pops again.
a) Pop 1: Stack S -> NULL
b) print "1"
c) current -> 3 /*right of 5 */
Step 3 pushes 3 to stack and makes current NULL
Stack S -> 3
current = NULL
Step 4 pops from S
a) Pop 3: Stack S -> NULL
b) print "3"
c) current = NULL /*right of 3 */
Traversal is done now as stack S is empty and current is NULL.
13. 13 http://coursehunt.net/
13: Printing binary tree level by level:
Level order traversal of the above tree is 1 2 3 4 5
Algorithm:
/*Function to print level order traversal of tree*/
printLevelorder(tree)
for d = 1 to height(tree)
printGivenLevel(tree, d);
/*Function to print all nodes at a given level*/
printGivenLevel(tree, level)
if tree is NULL then return;
if level is 1, then
print(tree->data);
else if level greater than 1, then
printGivenLevel(tree->left, level-1);
printGivenLevel(tree->right, level-1);
Time Complexity: O(n^2) in worst case
14. 14 http://coursehunt.net/
14: Reverse level order traversal of binary tree
Reverse Level order traversal of the above tree is “4 5 2 3 1”.
METHOD 1 (Recursive function to print a given level):
we have a method printGivenLevel() which prints a given level number. The only
thing we need to change is, instead of calling printGivenLevel() from first level to last level,
we call it from last level to first level.
Time Complexity: The worst case time complexity of this method is O(n^2).
METHOD 2 (Using Queue and Stack):
Use a stack to get the reverse level order. If we do normal level order traversal and
instead of printing a node, push the node to a stack and then print contents of stack, we get “5
4 3 2 1” for above example tree, but output should be “4 5 2 3 1”. So to get the correct
sequence (left to right at every level), we process children of a node in reverse order, we first
push the right subtree to stack, then left subtree.
15: Tree traversal spiral order:
For below tree, function should print 1, 2, 3, 4, 5, 6, 7.
Method 1 (Recursive):
To print the nodes in spiral order, nodes at different levels should be printed in
alternating order. An additional Boolean variable ltr is used to change printing order of levels.
15. 15 http://coursehunt.net/
If ltr is 1 then printGivenLevel() prints nodes from left to right else from right to left. Value
of ltr is flipped in each iteration to change the order.
Function to print level order traversal of tree:
printSpiral(tree)
bool ltr = 0;
for d = 1 to height(tree)
printGivenLevel(tree, d, ltr);
ltr ~= ltr /*flip ltr*/
Function to print all nodes at a given level
printGivenLevel(tree, level, ltr)
if tree is NULL then return;
if level is 1, then
print(tree->data);
else if level greater than 1, then
if(ltr)
printGivenLevel(tree->left, level-1, ltr);
printGivenLevel(tree->right, level-1, ltr);
else
printGivenLevel(tree->right, level-1, ltr);
printGivenLevel(tree->left, level-1, ltr);