Binary Tree in Java
Binary Tree in Java
Binary Tree in Java
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
Example of binary tree:
I have posted various programs on binary tree so that you can practice them
for interviews and it will also help in understanding recursion.
Binary tree traversals:
PreOrder traversal - In PreOrder traversal,each node is processed before either
of its sub-trees.In simpler words,Visit each node before its children.
InOrder traversal : In InOrder traversal,each node is processed between
subtrees.In simpler words,Visit left subtree, node and then right subtree.
PostOrder traversal: In PostOrder traversal,each node is processed after
subtrees traversal.In simpler words,Visit left subtree, right subtree and then
node.
Level order traversal : In Level order traversal, tree is traversed by each level.
It is same as breadth first search.
Spiral/Zigzag order traversal : In spiral order traversal, tree is traversed in
spiral shape.
Binary tree reverse level order traversal: It is similar to level order but in
reverse
Binary tree boundary traversal : This traversal traverse boundary of binary tree
Recursive
Iterative
Recursive solution:
Recursive solution is very straight forward.Below diagram will make you
understand recursion better.
if(root != null) {
//Visit the node by Printing the node data
4.
System.out.printf("%d ",root.data);
5.
preorder(root.left);
6.
preorder(root.right);
7.
8.
}
}
Iterative solution:
For recursion, we use implicit stack. So here to convert recursive solution to
We are pushing right child first, so it will be processed after left subtree as
Stack is LIFO.
view plainprint?
1.
2. public void preorderIter(TreeNode root) {
3.
4.
5.
if(root == null)
return;
6.
7.
8.
stack.push(root);
9.
10.
while(!stack.empty()){
11.
12.
TreeNode n = stack.pop();
13.
System.out.printf("%d ",n.data);
14.
15.
16.
if(n.right != null){
17.
stack.push(n.right);
18.
19.
if(n.left != null){
20.
stack.push(n.left);
21.
22.
23.
24.
25.
Example:
Lets say your binary tree is :
10. {
11. int data;
12. TreeNode left;
13. TreeNode right;
14. TreeNode(int data)
15. {
16.
this.data=data;
17. }
18. }
19.
20.
// Recursive Solution
if(root != null) {
23.
24.
System.out.printf("%d ",root.data);
25.
preorder(root.left);
26.
preorder(root.right);
27.
28. }
29.
if(root == null)
34.
return;
35.
36.
37.
stack.push(root);
38.
39.
while(!stack.empty()){
40.
41.
TreeNode n = stack.pop();
42.
System.out.printf("%d ",n.data);
43.
44.
45.
if(n.right != null){
46.
stack.push(n.right);
47.
48.
if(n.left != null){
49.
stack.push(n.left);
50.
51.
52.
53.
54.
55.
56. public static void main(String[] args)
57. {
58. BinaryTree bi=new BinaryTree();
59. // Creating a binary tree
60. TreeNode rootNode=createBinaryTree();
61. System.out.println("Using Recursive solution:");
62.
63. bi.preorder(rootNode);
64.
65. System.out.println();
66. System.out.println("-------------------------");
67. System.out.println("Using Iterative solution:");
68.
69. bi.preorderIter(rootNode);
70. }
71.
72. public static TreeNode createBinaryTree()
73. {
74.
75. TreeNode rootNode =new TreeNode(40);
76. TreeNode node20=new TreeNode(20);
77. TreeNode node10=new TreeNode(10);
Recursive
Iterative
Recursive solution:
Recursive solution is very straight forward.Below diagram will make you
understand recursion better.
Iterative solution:
Steps for iterative solution:
package org.arpit.java2blog;
import java.util.Stack;
public class BinaryTree {
public static class TreeNode
{
int data;
TreeNode left;
TreeNode right;
TreeNode(int data)
{
this.data=data;
}
}
// Recursive Solution
public void postOrder(TreeNode root) {
if(root != null) {
postOrder(root.left);
postOrder(root.right);
//Visit the node by Printing the node data
System.out.printf("%d ",root.data);
}
}
// Iterative solution
public void postorderIter( TreeNode root) {
if( root == null ) return;
Stack<TreeNode> s = new Stack<TreeNode>( );
TreeNode current = root;
while( true ) {
if( current != null ) {
if( current.right != null )
s.push( current.right );
s.push( current );
current = current.left;
continue;
}
if( s.isEmpty( ) )
return;
current = s.pop( );
if( current.right != null && ! s.isEmpty( ) && current.right ==
s.peek( ) ) {
s.pop( );
s.push( current );
current = current.right;
} else {
System.out.print( current.data + " " );
current = null;
}
}
}
public static void main(String[] args)
{
BinaryTree bi=new BinaryTree();
// Creating a binary tree
TreeNode rootNode=createBinaryTree();
System.out.println("Using Recursive solution:");
bi.inOrder(rootNode);
System.out.println();
System.out.println("-------------------------");
System.out.println("Using Iterative solution:");
bi.inOrderIter(rootNode);
}
public static TreeNode createBinaryTree()
{
TreeNode
TreeNode
TreeNode
TreeNode
TreeNode
TreeNode
TreeNode
rootNode.left=node20;
rootNode.right=node60;
node20.left=node10;
node20.right=node30;
node60.left=node50;
node60.right=node70;
return rootNode;
Recursive
Iterative
Recursive solution:
Recursive solution is very straight forward.Below diagram will make you
understand recursion better.
if(root != null) {
3.
inOrder(root.left);
4.
5.
System.out.printf("%d ",root.data);
6.
inOrder(root.right);
7.
8.
}
}
Iterative solution:
For recursion, we use implicit stack. So here to convert recursive solution to
iterative, we will use explicit stack.
Steps for iterative solution:
1. Create an empty stack s and Initialize current node as root
4. If stack is empty and currentNode is also null then we are done with it
view plainprint?
1.
2. public void inOrderIter(TreeNode root) {
3.
4.
5.
if(root == null)
return;
6.
7.
8.
TreeNode currentNode=root;
9.
10. while(!s.empty() || currentNode!=null){
11.
12.
if(currentNode!=null)
13.
14.
s.push(currentNode);
15.
currentNode=currentNode.left;
16.
17.
else
18.
19.
TreeNode n=s.pop();
20.
System.out.printf("%d ",n.data);
21.
currentNode=n.right;
22.
23. }
24. }
10. {
11. int data;
12. TreeNode left;
13. TreeNode right;
14. TreeNode(int data)
15. {
16.
this.data=data;
17. }
18. }
19.
20.
// Recursive Solution
inOrder(root.left);
24.
25.
System.out.printf("%d ",root.data);
26.
inOrder(root.right);
27. }
28. }
29.
30. // Iterative solution
31. public void inOrderIter(TreeNode root) {
32.
33. if(root == null)
34.
return;
35.
36. Stack<TreeNode> s = new Stack<TreeNode>();
37. TreeNode currentNode=root;
38.
39. while(!s.empty() || currentNode!=null){
40.
41.
if(currentNode!=null)
42.
43.
s.push(currentNode);
44.
currentNode=currentNode.left;
45.
46.
else
47.
48.
TreeNode n=s.pop();
49.
System.out.printf("%d ",n.data);
50.
currentNode=n.right;
51.
52. }
53. }
54.
55. public static void main(String[] args)
56. {
57. BinaryTree bi=new BinaryTree();
58. // Creating a binary tree
59. TreeNode rootNode=createBinaryTree();
60. System.out.println("Using Recursive solution:");
61.
62. bi.inOrder(rootNode);
63.
64. System.out.println();
65. System.out.println("-------------------------");
66. System.out.println("Using Iterative solution:");
67.
68. bi.inOrderIter(rootNode);
69. }
70.
71. public static TreeNode createBinaryTree()
72. {
73.
74. TreeNode rootNode =new TreeNode(40);
75. TreeNode node20=new TreeNode(20);
76. TreeNode node10=new TreeNode(10);
77. TreeNode node30=new TreeNode(30);
78. TreeNode node60=new TreeNode(60);
79. TreeNode node50=new TreeNode(50);
80. TreeNode node70=new TreeNode(70);
81.
82. rootNode.left=node20;
83. rootNode.right=node60;
84.
85. node20.left=node10;
86. node20.right=node30;
87.
88. node60.left=node50;
89. node60.right=node70;
90.
91. return rootNode;
92. }
93.}
Run above program and you will get following output:
view plainprint?
1.
2. Using Recursive solution:
3. 10 20 30 40 50 60 70
4. ------------------------5. Using Iterative solution:
6. 10 20 30 40 50 60 70
We will use Queue for Level Order traversal.This algorithm is very similar to
Breadth first search of graph.
Steps for Level order traversal algorithm:
1. Create empty queue and pust root node to it.
2. Do the following when queue is not empty
o
while(!queue.isEmpty())
{
TreeNode tempNode=queue.poll();
System.out.printf("%d ",tempNode.data);
if(tempNode.left!=null)
queue.add(tempNode.left);
if(tempNode.right!=null)
queue.add(tempNode.right);
}
}
Example:
Lets say your binary tree is :
package org.arpit.java2blog;
import java.util.Queue;
import java.util.LinkedList;
public class BinaryTree {
public static class TreeNode
{
int data;
TreeNode left;
TreeNode right;
TreeNode(int data)
{
this.data=data;
}
}
// prints in level order
public static void levelOrderTraversal(TreeNode startNode) {
Queue<TreeNode> queue=new LinkedList<TreeNode>();
queue.add(startNode);
while(!queue.isEmpty())
{
TreeNode tempNode=queue.poll();
System.out.printf("%d ",tempNode.data);
if(tempNode.left!=null)
queue.add(tempNode.left);
if(tempNode.right!=null)
queue.add(tempNode.right);
}
}
public static void main(String[] args)
{
BinaryTree bi=new BinaryTree();
// Creating a binary tree
TreeNode rootNode=createBinaryTree();
System.out.println("Level Order traversal of binary tree will be:");
levelOrderTraversal(rootNode);
}
public static TreeNode createBinaryTree()
{
TreeNode
TreeNode
TreeNode
TreeNode
TreeNode
TreeNode
TreeNode
rootNode.left=node20;
rootNode.right=node60;
node20.left=node10;
node20.right=node30;
node60.left=node50;
node60.right=node70;
return rootNode;
}
}
stack=tempStack;
Example:
Lets say your binary tree is :
package org.arpit.java2blog;
import java.util.Queue;
import java.util.LinkedList;
public class BinaryTree {
public static class TreeNode
{
int data;
TreeNode left;
TreeNode right;
TreeNode(int data)
{
this.data=data;
}
}
// prints spiral/zigzag level order
public static void spiralOrZigzagLevelOrder(TreeNode root) {
if(root==null) return;
Stack<TreeNode> stack=new Stack<TreeNode>();
stack.push(root);
boolean directionflag=false;
while(!stack.isEmpty())
{
stack=tempStack;
}
public static void main(String[] args)
{
BinaryTree bi=new BinaryTree();
// Creating a binary tree
TreeNode rootNode=createBinaryTree();
System.out.println("Spiral/Zigzag traversal of binary tree :");
spiralOrZigzagLevelOrder(rootNode);
}
public static TreeNode createBinaryTree()
{
TreeNode
TreeNode
TreeNode
TreeNode
TreeNode
TreeNode
TreeNode
TreeNode
TreeNode
rootNode.left=node20;
rootNode.right=node60;
node20.left=node10;
node20.right=node30;
node60.left=node50;
node60.right=node70;
node10.left=node5;
node50.right=node55;
return rootNode;
}
}
Example:
Lets say your binary tree is :
package org.arpit.java2blog;
import
import
import
public
java.util.LinkedList;
java.util.Queue;
java.util.Stack;
class BinaryTree {
while(!queue.isEmpty())
{
TreeNode tempNode=queue.poll();
if(tempNode.right!=null)
queue.add(tempNode.right);
if(tempNode.left!=null)
queue.add(tempNode.left);
stack.push(tempNode);
}
while(!stack.empty())
System.out.print(stack.pop().data+" " );
}
public static void main(String[] args)
{
BinaryTree bi=new BinaryTree();
// Creating a binary tree
TreeNode rootNode=createBinaryTree();
System.out.println("Reverse Level Order traversal of binary tree will
be:");
reverseLevelOrderTraversal(rootNode);
}
public static TreeNode createBinaryTree()
{
TreeNode
TreeNode
TreeNode
TreeNode
TreeNode
TreeNode
TreeNode
rootNode.left=node20;
rootNode.right=node60;
node20.left=node10;
node20.right=node30;
node60.left=node50;
node60.right=node70;
return rootNode;
}
If you look closely to above diagram, boundary traversals can be divided into
three essential parts
return;
// if leaf node, ignore while printing edges
if(root.left==null && root.right==null)
return;
System.out.print(root.data+" ");
// If left is null, right will be the boundary edge.
if(root.left==null)
{
printLeftEdgeNodes(root.right);
}
else
{
printLeftEdgeNodes(root.left);
}
}
if(root.right!=null)
{
printRightBottomUp(root.right);
}
else if(root.left!=null)
{
printRightBottomUp(root.left);
}
System.out.print(root.data+" ");
}
TreeNode
TreeNode
TreeNode
TreeNode
TreeNode
node50=new TreeNode(50);
node70=new TreeNode(70);
node5=new TreeNode(5);
node45=new TreeNode(45);
node55=new TreeNode(55);
rootNode.left=node20;
rootNode.right=node60;
node20.left=node10;
node20.right=node30;
node60.left=node50;
node60.right=node70;
node10.right=node5;
node5.right=node45;
node50.right=node55;
return rootNode;
}
}
When you run above program, you will get below output:
Boundary traversal of binary tree will be:
40 20 10 5 45 30 55 70 60
if(node==null)
5.
return;
6.
7.
8.
9.
10. printLeafNodes(node.left);
11. printLeafNodes(node.right);
12.}
Example:
Binary tree:
5.
6.
7.
8.
9.
int data;
this.data=data;
15. }
16. }
17.
18. // Recursive Solution
19. // print leaf nodes
20. public static void printLeafNodes(TreeNode node) {
21.
22.
23.
if(node==null)
return;
24.
25.
26.
27.
28.
printLeafNodes(node.left);
29.
printLeafNodes(node.right);
30. }
31.
32.
33.
34. public static void main(String[] args)
35. {
36. BinaryTree bi=new BinaryTree();
37. // Creating a binary tree
38. System.out.println("Printing leaf nodes in binary tree :");
39. printLeafNodes(rootNode);
40. }
41.
42. public static TreeNode createBinaryTree()
43. {
44.
45. TreeNode rootNode =new TreeNode(40);
46. TreeNode node20=new TreeNode(20);
47. TreeNode node10=new TreeNode(10);
48. TreeNode node30=new TreeNode(30);
49. TreeNode node60=new TreeNode(60);
50. TreeNode node50=new TreeNode(50);
51. TreeNode node70=new TreeNode(70);
52.
package org.arpit.java2blog;
public class BinaryTree {
public static class TreeNode
{
int data;
TreeNode left;
TreeNode right;
TreeNode(int data)
{
this.data=data;
}
}
// Recursive Solution
/* To get the count of leaf nodes in a binary tree*/
public static int getLeafCountOfBinaryTree(TreeNode node)
{
if(node == null)
return 0;
if(node.left ==null && node.right==null)
return 1;
else
return getLeafCountOfBinaryTree(node.left)+
getLeafCountOfBinaryTree(node.right);
}
public static void main(String[] args)
{
BinaryTree bi=new BinaryTree();
// Creating a binary tree
TreeNode rootNode=createBinaryTree();
System.out.println("Number of leaf nodes in binary
tree :"+getLeafCountOfBinaryTree(rootNode));
}
public static TreeNode createBinaryTree()
{
TreeNode
TreeNode
TreeNode
TreeNode
TreeNode
TreeNode
TreeNode
rootNode.left=node20;
rootNode.right=node60;
node20.left=node10;
node20.right=node30;
node60.left=node50;
node60.right=node70;
return rootNode;
}
Algorithm:
Steps for print all paths from root to leaf are:
path[len] = node.data;
len++;
if(node.left == null && node.right == null) {
// leaf node is reached
printArray(path,len);
return;
}
printAllPathsToLeaf(node.left, path, len);
printAllPathsToLeaf(node.right, path, len);
}
package org.arpit.java2blog;
public class BinaryTree {
public static class TreeNode
{
int data;
TreeNode left;
TreeNode right;
TreeNode(int data)
{
this.data=data;
}
}
// Prints all paths to leaf
public static void printAllPathsToLeaf(TreeNode node, int[] path, int
len) {
if ( node == null )
return;
// storing data in array
path[len] = node.data;
len++;
if(node.left == null && node.right == null) {
// leaf node is reached
printArray(path,len);
return;
}
{
BinaryTree bi=new BinaryTree();
// Creating a binary tree
TreeNode rootNode=createBinaryTree();
System.out.println("Printing all paths from root to leaf :");
printAllPathsToLeaf(rootNode,new int[1000],0);
rootNode.left=node20;
rootNode.right=node60;
node20.left=node10;
node20.right=node30;
node60.left=node50;
node60.right=node70;
node10.left=node5;
node50.right=node55;
return rootNode;
}
}
Recursive
Iterative
Recursive solution:
Algorithm :
Steps for getting maximum element in binary tree:
// Recursive Solution
int max=Integer.MIN_VALUE;
6.
int value=0;
7.
int left,right;
8.
if(root != null)
9.
10. value=root.data;
11. left=getMaximumRec(root.left);
12. right=getMaximumRec(root.right);
13.
14. if(left>right)
15. {
16.
max=left;
17. }
18. else
19. {
20.
max=right;
21. }
22.
23. if(max < value)
24. {
25.
max=value;
26. }
27. }
28.
29. return max;
30.}
Iterative solution:
Iterative solution will be similar to level order traversal. When we are popping
element from queue, we will check max.
Code for iteration will be :
view plainprint?
1.
// Iterative Solution
5.
6.
queue.add(startNode);
7.
int max=Integer.MIN_VALUE;
8.
while(!queue.isEmpty())
9.
max=tempNode.data;
13. if(tempNode.left!=null)
14.
queue.add(tempNode.left);
15. if(tempNode.right!=null)
16.
queue.add(tempNode.right);
17. }
18. return max;
19.}
view plainprint?
1. package org.arpit.java2blog;
2.
3. import java.util.LinkedList;
4. import java.util.Queue;
5.
6. public class BinaryTree {
7.
/*
8.
9.
*/
10.
11. public static class TreeNode
12. {
13. int data;
14. TreeNode left;
15. TreeNode right;
16. TreeNode(int data)
17. {
18.
this.data=data;
19. }
20. }
21.
22. // Recursive Solution
23. /* To get max node in a binary tree*/
24. public static int getMaximumRec(TreeNode root)
25. {
26. int max=Integer.MIN_VALUE;
27. int value=0;
28. int left,right;
29. if(root != null)
30. {
31.
value=root.data;
32.
left=getMaximumRec(root.left);
33.
right=getMaximumRec(root.right);
34.
35.
if(left>right)
36.
37.
max=left;
38.
39.
else
40.
41.
42.
max=right;
}
43.
44.
45.
46.
47.
max=value;
}
48. }
49.
50. return max;
51. }
52.
53. // Iterative Solution
54. /* To get max node in a binary tree*/
55. public static int getMaximumItr(TreeNode startNode) {
56.
57. Queue<TreeNode> queue=new LinkedList<TreeNode>();
58. queue.add(startNode);
59. int max=Integer.MIN_VALUE;
60. while(!queue.isEmpty())
61. {
62.
TreeNode tempNode=queue.poll();
63.
64.
max=tempNode.data;
65.
if(tempNode.left!=null)
66.
67.
queue.add(tempNode.left);
if(tempNode.right!=null)
68.
queue.add(tempNode.right);
69. }
70. return max;
71. }
72.
73.
74. public static void main(String[] args)
75. {
76. BinaryTree bi=new BinaryTree();
77. // Creating a binary tree
78. TreeNode rootNode=createBinaryTree();
79. System.out.println("Max node using recursion :"+getMaximumRec(root
Node));
80. System.out.println("Max node using iteration :"+getMaximumItr(rootNo
de));
81. }
82.
83. public static TreeNode createBinaryTree()
84. {
85.
86. TreeNode rootNode =new TreeNode(40);
87. TreeNode node20=new TreeNode(20);
88. TreeNode node10=new TreeNode(10);
89. TreeNode node30=new TreeNode(30);
90. TreeNode node60=new TreeNode(60);
91. TreeNode node50=new TreeNode(50);
92. TreeNode node70=new TreeNode(70);
93.
94. rootNode.left=node20;
95. rootNode.right=node60;
96.
97. node20.left=node10;
98. node20.right=node30;
99.
100.
node60.left=node50;
101.
node60.right=node70;
102.
103.
104.
105.
return rootNode;
}
}
Algorithm:
Steps for print vertical sum of binary tree:
Create a variable level and initialise it with 0. When you traverse left
child, decrease level by 1(level--) and when you traverse right child,
increase level by 1(level++).
Once TreeMap is populated after iterating all nodes, print the results.
Please find diagram below which shows level assigned for each binary tree
node.
Example:
Lets create java program for printing vertical sum in binary tree:
package org.arpit.java2blog;
import java.util.Map.Entry;
import java.util.TreeMap;
public class BinaryTreeVerticalSumMain {
public static class TreeNode
{
int data;
TreeNode left;
TreeNode right;
TreeNode(int data)
{
this.data=data;
}
}
rootNode.left=node20;
rootNode.right=node60;
node20.left=node10;
node20.right=node30;
node60.left=node50;
node60.right=node70;
node50.right=node55;
node30.left=node5;
return rootNode;
}
Algorithm :
Steps for getting level of a node in binary tree:
return result;
}
result= getLevelOfNode(root.right,key,level+1);
return result;
package org.arpit.java2blog;
public class BinaryTree {
public static class TreeNode
{
int data;
TreeNode left;
TreeNode right;
TreeNode(int data)
{
this.data=data;
}
}
// Recursive Solution
//To get level of node in a binary tree
public static int getLevelOfNode(TreeNode root,int key,int level)
{
if(root==null)
return 0;
if(root.data==key)
return level;
int result=getLevelOfNode(root.left,key,level+1) ;
if(result!=0)
{
// If found in left subtree , return
return result;
}
result= getLevelOfNode(root.right,key,level+1);
return result;
}
public static void main(String[] args)
{
BinaryTree bi=new BinaryTree();
// Creating a binary tree
TreeNode rootNode=createBinaryTree();
System.out.println("Node data: 70,Level :"+getLevelOfNode(rootNode, 70,
1));
System.out.println("Node data: 100,Level :"+getLevelOfNode(rootNode,
100, 1));
System.out.println("Node data: 60,Level :"+getLevelOfNode(rootNode, 60,
1));
System.out.println("Node data: 40,Level :"+getLevelOfNode(rootNode, 40,
1));
}
public static TreeNode createBinaryTree()
{
TreeNode
TreeNode
TreeNode
TreeNode
TreeNode
TreeNode
TreeNode
rootNode.left=node20;
rootNode.right=node60;
node20.left=node10;
node20.right=node30;
node60.left=node50;
node60.right=node70;
return rootNode;
}
}
Node
Node
Node
Node
data:
data:
data:
data:
70,Level :3
100,Level :0
60,Level :2
40,Level :1
Algorithm :
Steps for getting level of a node in binary tree:
8.
9.
int result=getLevelOfNode(root.left,key,level+1) ;
10. if(result!=0)
11. {
12.
13.
return result;
14.
15. }
view plainprint?
1. package org.arpit.java2blog;
2.
3. public class BinaryTree {
4.
5.
6.
7.
8.
int data;
9.
TreeNode left;
13.
this.data=data;
14. }
15. }
16.
17. // Recursive Solution
18.//To get level of node in a binary tree
19. public static int getLevelOfNode(TreeNode root,int key,int level)
20. {
21. if(root==null)
22.
return 0;
23. if(root.data==key)
24.
return level;
25.
26. int result=getLevelOfNode(root.left,key,level+1) ;
27. if(result!=0)
28. {
29.
30.
return result;
31. }
32. result= getLevelOfNode(root.right,key,level+1);
33.
34. return result;
35. }
36.
37.
38. public static void main(String[] args)
39. {
40. BinaryTree bi=new BinaryTree();
41. // Creating a binary tree
42. TreeNode rootNode=createBinaryTree();
43. System.out.println("Node data: 70,Level :"+getLevelOfNode(rootNode,
70, 1));
44. System.out.println("Node data: 100,Level :"+getLevelOfNode(rootNode,
100, 1));
45. System.out.println("Node data: 60,Level :"+getLevelOfNode(rootNode,
60, 1));
46. System.out.println("Node data: 40,Level :"+getLevelOfNode(rootNode,
40, 1));
47. }
48.
49. public static TreeNode createBinaryTree()
50. {
51.
52. TreeNode rootNode =new TreeNode(40);
53. TreeNode node20=new TreeNode(20);
54. TreeNode node10=new TreeNode(10);
55. TreeNode node30=new TreeNode(30);
56. TreeNode node60=new TreeNode(60);
57. TreeNode node50=new TreeNode(50);
58. TreeNode node70=new TreeNode(70);
59.
60. rootNode.left=node20;
61. rootNode.right=node60;
62.
63. node20.left=node10;
64. node20.right=node30;
65.
66. node60.left=node50;
67. node60.right=node70;
68.
69. return rootNode;
70. }
71.}
Run above program and you will get following output:
view plainprint?
1.
2. Node data: 70,Level :3
3. Node data: 100,Level :0
4. Node data: 60,Level :2
5. Node data: 40,Level :1
Lowest Common Ancestor (LCA) of binary tree in java
In this post, we will see how to find lowest common ancestor(LCA) of two nodes
in binary tree. Lets understand with example.
As you can see here, LCA is nothing but lowest common parent of two nodes.
If we get both left and right for any node as not null, it will be lowest
common ancestor of two given nodes
view plainprint?
1. public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode
a, TreeNode b) {
2.
if(root == null)
3.
return null;
4.
5.
return root;
6.
7.
TreeNode left=lowestCommonAncestor(root.left,a,b);
8.
TreeNode right=lowestCommonAncestor(root.right,a,b);
9.
10.
11.
12.
return root;
13.
if(left== null)
14.
return right;
15.
else
16.
return left;
17.
18.
6.
7.
int data;
8.
TreeNode left;
9.
TreeNode right;
this.data=data;
13. }
14. }
15.
16. public static TreeNode lowestCommonAncestor(TreeNode root, TreeNod
e a, TreeNode b) {
17.
if(root == null)
18.
return null;
19.
20.
return root;
21.
22.
TreeNode left=lowestCommonAncestor(root.left,a,b);
23.
TreeNode right=lowestCommonAncestor(root.right,a,b);
24.
25.
26.
27.
return root;
28.
if(left== null)
29.
return right;
30.
else
31.
return left;
32.
33.
Algorithm:
Steps for print vertical sum of binary tree:
Create a variable level and initialise it with 0. When you traverse left
child, decrease level by 1(level--) and when you traverse right child,
increase level by 1(level++).
TreeMap has entry with (0,40) where 0 is level and 40 is node data. So
while traversing, if you encountered node 30 at level 0, so after
processing node 30, TreeMap will have entry as (0,70)
Once TreeMap is populated after iterating all nodes, print the results.
3.
if(startNode==null)
4.
5.
6.
return;
}
7.
8.
9.
printVertivalSumOfBinaryTree(startNode.left,treeNodeMap,level-1);
10.
11. if(treeNodeMap.get(level)!=null)
12. {
13.
14.
// Adding current node data to previous stored value to get the sum
Integer sum=treeNodeMap.get(level)+startNode.data;
15.
16. }
17. else
18. {
19.
treeNodeMap.put(level, sum);
20.
treeNodeMap.put(level, startNode.data);
21. }
22. // Increase level by 1 when iterating left child
23. printVertivalSumOfBinaryTree(startNode.right,treeNodeMap,level+1);
24.
25. }
Please find diagram below which shows level assigned for each binary tree
node.
Example:
Lets create java program for printing vertical sum in binary tree:
view plainprint?
1.
2.
3. package org.arpit.java2blog;
4.
5. import java.util.Map.Entry;
6. import java.util.TreeMap;
7.
8. public class BinaryTreeVerticalSumMain {
9.
10.
11. public static class TreeNode
12. {
13. int data;
14. TreeNode left;
15. TreeNode right;
16. TreeNode(int data)
17. {
18.
this.data=data;
19. }
20. }
21.
22.// prints vertical sum of binary tree
23. public static void printVertivalSumOfBinaryTree(TreeNode startNode,Tree
Map<Integer,Integer> treeNodeMap,int level) {
24. if(startNode==null)
25. {
26.
return;
27. }
28.
29. // Decrease level by 1 when iterating left child
30. printVertivalSumOfBinaryTree(startNode.left,treeNodeMap,level-1);
31.
32. if(treeNodeMap.get(level)!=null)
33. {
34.
Integer sum=treeNodeMap.get(level)+startNode.data;
35.
// Adding current node data to previous stored value to get the sum
36.
treeNodeMap.put(level, sum);
37. }
38. else
39. {
40.
41.
treeNodeMap.put(level, startNode.data);
42. }
43. // Increase level by 1 when iterating left child
44. printVertivalSumOfBinaryTree(startNode.right,treeNodeMap,level+1);
45.
46. }
47. public static void main(String[] args)
48. {
49. BinaryTreeVerticalSumMain bi=new BinaryTreeVerticalSumMain();
74. rootNode.right=node60;
75.
76. node20.left=node10;
77. node20.right=node30;
78.
79. node60.left=node50;
80. node60.right=node70;
81. node50.right=node55;
82. node30.left=node5;
83. return rootNode;
84. }
85.}
Run above program and you will get following output:
view plainprint?
1.
2. Vertical sum of binary tree will be:
3. 10
4. 25
5. 120
6. 115
7. 70
8.