Is there a way to find the height of a tree which is not necessarily binary? There are many algorithms for the height of a binary tree but none of them will work for a non-b
It is possible. We can do by below approach.
package com.ds;
import java.util.Arrays;
public class TreeNode {
private Integer data;
private TreeNode[] children;
public TreeNode() {
super();
}
public TreeNode(Integer data) {
super();
this.data = data;
}
public void setChildren(TreeNode[] children) {
this.children = children;
}
public Integer maxDepth(TreeNode treeNode) {
Integer depth = 0;
if (treeNode.children != null) {
if (treeNode.children.length == 0) {
return depth;
} else {
for (int i = 0; i < treeNode.children.length; i++) {
depth = Math.max(depth, this.maxDepth(treeNode.children[i]));
}
return depth + 1;
}
} else {
return depth;
}
}
@Override
public String toString() {
return "TreeNode [data=" + data + ", children=" + Arrays.toString(children) + "]";
}
public static void main(String[] args) {
TreeNode t1 = new TreeNode(1);
TreeNode t2 = new TreeNode(2);
TreeNode t3 = new TreeNode(3);
TreeNode t4 = new TreeNode(4);
TreeNode t5 = new TreeNode(5);
TreeNode t6 = new TreeNode(6);
TreeNode t7 = new TreeNode(7);
TreeNode t8 = new TreeNode(8);
TreeNode t9 = new TreeNode(9);
TreeNode t10 = new TreeNode(10);
TreeNode t11 = new TreeNode(11);
TreeNode t12 = new TreeNode(12);
TreeNode t101 = new TreeNode(101);
TreeNode[] childOf1 = { t2, t3 };
TreeNode[] childOf2 = { t4, t5, t101 };
TreeNode[] childOf3 = { t6, t7 };
TreeNode[] childOf4 = { t8, t9 };
TreeNode[] childOf6 = { t10 };
TreeNode[] childOf10 = { t11, t12 };
t1.setChildren(childOf1);
t2.setChildren(childOf2);
t3.setChildren(childOf3);
t4.setChildren(childOf4);
t6.setChildren(childOf6);
t10.setChildren(childOf10);
TreeNode obj = new TreeNode();
Integer depth = obj.maxDepth(t1);
System.out.println("Depth- " + depth);
}
}