"Prove safety offer" - the follow-up traversal sequence of binary search tree (Java)

Title Description

Enter an integer array, the array is not the result of the determination after traversing a binary search tree. If the output Yes, otherwise the output No. Suppose the input array of any two numbers are different from each other.

public class Solution {
    public boolean VerifySquenceOfBST(int [] sequence) {
        
    }
}

 

Ideas:

Recalling the first to know binary search tree:

Binary search tree (Binary Search Tree), (Also: a binary search tree, binary sort tree) which is either an empty tree, or having the following properties of a binary tree : If it's left subtree is not empty, then left values of all the sub-tree nodes are less than the value of the root node; if its right subtree is not empty, then the right sub-tree, all the nodes which are greater than the value of the root; its left , they were also right subtree binary sort tree .
Column such as:

We write about the follow-up to traverse above the binary search tree (about root):

2,5,3,8,7,6 

According to these rules and the subsequent traversal binary search tree, we can know:

  1. The last element is the root node;
  2. Larger than the last element is the element of the right subtree of the tree; the tree is smaller than the last one, is an element in the left subtree of the tree;

To sum up, we can be divided into a tree [2,5,3] [8,7] [6]

Wherein [6] is the root, [2,5,3] is a subsequent traverse left subtree, [8,7] is a subsequent traverse right subtree.

We can be divided into sub-tree out of the left and right sub-tree before continuing division as described above;

Until The End element division, the division process, if there is no violation of the rules binary search tree, it shows that change is follow the subsequent traversal traverse a binary search tree.

 

achieve:

public class Solution {
    public boolean VerifySquenceOfBST(int [] sequence) {
        if (sequence == null || sequence.length == 0)
            return false;
        return check(sequence,0,sequence.length - 1);
    }
    
    private boolean check(int[] sequence, int first, int last){
        if (last - first <= 1)
            return true;
        int rootVal = sequence[last];
        int cutIndex = first;
        while (cutIndex < last && sequence[cutIndex] <= rootVal)
            cutIndex++;
        for (int i = cutIndex; i < last; i ++)
            if (sequence[i] < rootVal)
                return false;
        return check(sequence,first,cutIndex - 1) && check(sequence,cutIndex,last -1);
    }
    
}

 

 

Published 74 original articles · won praise 20 · views 1886

Guess you like

Origin blog.csdn.net/love_MyLY/article/details/103980920