Friday, September 13, 2013

print the longest path in BST


    public void printMaxPath() {
        int len = getHeight(root);
        int[] arr1 = new int[50];
        int[] arr2 = new int[2 * len - 1];
        int count = -1;
        if (root == null) {
            return;
        }
        System.out.print("\n print path  \n");
        //  ++count;
        //   arr1[count] = root.data;
        //   arr2[count] = root.data;
        //System.out.print(root.data+" : ");
        //printMaxPath(root.leftChild, arr1, arr2, count);
        printMaxPath(root, arr1, count);
        for (int i : arr1) {
            System.out.print(i + " : ");
        }
        System.out.print("\n");
        for (int i : arr2) {
            System.out.print(i + " : ");
        }
    }

    private void printMaxPath(Node node) {
        if (node.leftChild != null && node.rightChild != null) {
            int lh = getHeight(node.leftChild);
            int rh = getHeight(node.rightChild);
            if (lh > rh) {
                node = node.leftChild;
                System.out.print(node.data + " : ");
                printMaxPath(node);
            } else {
                node = node.rightChild;
                System.out.print(node.data + " : ");
                printMaxPath(node);
            }
        } else if (node.leftChild != null) {
            node = node.leftChild;
            System.out.print(node.data + " : ");
            printMaxPath(node);
        } else if (node.rightChild != null) {
            node = node.rightChild;
            System.out.print(node.data + " : ");
            printMaxPath(node);
        } else {
            return;
        }
    }

No comments:

Post a Comment