Java implements post-order traversal sequence of binary search tree

Input an integer array to determine whether the array is the result of a post-order traversal of a binary search tree. Returns true if yes, false otherwise. Suppose any two numbers of the input array are different from each other.

code

    static boolean isLastOrder(int[] lastOrder, int start, int end) {
        if (lastOrder == null || start < 0 || end < 0 || start > end) {
            return false;
        }
        int length = lastOrder.length;
        if (start >= length || end >= length) {
            return false;
        }

        // Postorder traversal of binary tree: left->right->root, so the last element of the array is the root of the binary tree
        int root = lastOrder[end];

        // The characteristic of searching a binary tree is that any node in the left subtree is smaller than the root node, and any node in the right subtree is larger than the root node
        // Combined with post-order traversal, find the node position greater than the last element of the array, then the previous elements belong to the left subtree
        int rightStart = start;
        while (rightStart < end) {
            // Find the split point of the left and right subtrees, starting from the left and then the right subtree
            if (lastOrder[rightStart] > root){
                break;
            }
            rightStart++;
        }
        int rightEnd = rightStart;
        while (rightEnd < end) {
            // If the right subtree has elements less than root, it means that it is not post-order traversal
            if (lastOrder[rightEnd] < root) {
                return false;
            }
            rightEnd++;
        }
        boolean leftIsLastOrder = true;
        // If the index of the starting element of the right subtree is greater than start, it means that the current root node has a left subtree
        if (rightStart > start) {
            leftIsLastOrder = isLastOrder(lastOrder, start, rightStart - 1);
        }
        boolean rightIsLastOrder = true;
        // If the index of the starting element of the right subtree is less than end - 1, it means that the current root node has a right subtree
        if (rightStart < end - 1) {
            rightIsLastOrder = isLastOrder(lastOrder, rightStart, end - 1);
        }

        // Both the left subtree and right subtree of the current root node satisfy postorder traversal
        return leftIsLastOrder && rightIsLastOrder;
    }

    public static void main(String[] args) {
        //           5
        //       3       18
        //   2       4
        // Postorder traversal is 2, 4, 3, 18, 5
        int[] order = {2, 4, 3, 18, 5};
        System.out.print(isLastOrder(order, 0, order.length - 1));
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325925709&siteId=291194637