Sunday, June 7, 2015

Diameter of a tree: Longest path between any two nodes

Diameter of a tree can be from any one of the following:
1. Longest path of the tree passes through the root
2. Longest path is completely in left sub tree
3. Longest path is completely in right sub tree

To find the Longest path passing through the root, is nothing but the height of the node, ie. "height(left) + height(right) + 1"

Other two can be find in recursive way.

Algorithm:
Each time we are trying to find out height of left/right sub trees. We can use an independent function to calculate height of tree, but that takes O(n) each time. Instead we can make the function to return height also along with diameter.

result[] = {diameter, height}

diameter passing through root is: rootDia=leftResult[1] + rightResult[1] + 1

leftDia = leftResult[0];
rightDia = rightResult[0];

result[1] = max(leftResult[1]+1, rightResult[1]);

return max(rootDia, max(leftDia, rightDia));

Code:

class DiameterOfTree {
        static public int[] getDia(TreeNode root) {
                int[] result = {0, 0};

                if(root == null)
                        return result;

                int[] leftRes = getDia(root.getLeft());
                int[] rightRes = getDia(root.getRight());

                int leftHt = leftRes[1];
                int rightHt = rightRes[1];

                int leftDia = leftRes[0];
                int rightDia = rightRes[0];

                result[0] = Math.max(leftHt+rightHt+1, Math.max(leftDia, rightDia));
                result[1] = Math.max(leftHt+1, rightHt+1);

                return result;
        }

        static public void main(String[] args) {
                System.out.println(getDia(TreeUtil.getBinaryTree())[0]);
                System.out.println(getDia(TreeUtil.getBinaryTree1())[0]);
        }
}


No comments:

Post a Comment