"Prove safety offer" face questions after 24 binary search tree preorder traversal sequence Java version

(Analyzing a sequence element is not the same whether a BST of LRD)

The book: First for binary search trees, all elements of the left sub-tree root node is less than less than all of the elements in the right subtree, and then the last element traversal sequence after sequence is the root, this is our condition known . This question is reminiscent preorder preamble sequence with a common binary tree (or subsequent) traversal sequence plus you can restore a binary tree, in that question, we know that the preamble sequence or the order will be able to They began to organize the root node, but because we can not determine the number of sub-tree, so it needs an auxiliary sequence to determine the scope of the sub-tree. But if the change in the preamble of BST or order traversal sequence, we can directly organize the binary tree, BST features to help us determine the scope of the sub-tree . For this question, we have to determine a sequence is not a sequence of BST postorder traversal, the same ideas can be used to determine the root node, but there is no need to rebuild a binary tree, we only need to determine two sequences is not valid in the current recursion on the line. We first find the root node (the last element), then use it to locate the split point about sub-tree to determine the right of the split point is not greater than the root, if it went to two sub-divided recursively check point on the left and right of the split point sequence.

        public boolean judge(int[] a){
            if(a == null)return false;
            if(a.length == 0)return true;
            return myJudge(a, 0, a.length-1);
        }
        
        private boolean myJudge(int[] a, int start, int end){
            //加上等号也可以
            if(start > end)return true;
            int leftEnd = start-1;
            for(int i=start; i<=end-1; i++){
                if(a[i]<a[end]){
                    leftEnd++;
                }
            }
            for(int i=leftEnd+1; i<=end-1; i++){
                if(a[i] < a[end]){
                    return false;
                }
            }
            return myJudge(a, start, leftEnd) && myJudge(a, leftEnd+1, end-1);
        }

Guess you like

Origin www.cnblogs.com/czjk/p/11640352.html