`

Zenefits Interview - Can represent the pre-order list of a BST

 
阅读更多
Given a list of numbers, determine whether it can represent the pre-order traversal list of a binary search tree (BST).
 
Input
The first line contains the number of test cases, TT lines follow, consisting of two lines each.
The first line of each test case contains the number of nodes in the tree, N. In next line there will a list of N unique numbers, where each number is from the range [1, N].
 
Output
For each test case, print the string “YES” if there exists a BST whose pre-order traversal is equal to the list, otherwise print the string “NO” (without quotes, preserving capitalization).
 
Constraints
1 ≤ T ≤ 10
1 ≤ N ≤ 100
 
Sample Input
5
3
1 2 3
3
2 1 3
6
3 2 1 5 4 6
4
1 3 4 2
5
3 4 5 1 2
 
Sample Output
YES
YES
YES
NO
NO
 
Explanation
  • The first three cases are from the above examples.
  • In case 4, after encountering the 3, the 4tells us we are on the right sub-tree, which means no values smaller than 3 are allowed any longer. So when we see the 2 we know the list is invalid.
  • Similarly, in case 5, after encountering the 3, the 4 and 5 tell us we are on the right sub-tree, so the subsequent encounter of values 2 and 1, which belong in the left sub-tree, tells us that the list is not valid as a pre-order traversal of a BST.
public static boolean isValidPreorderBST(int[] A) {
	return isValidPreorderBST(A, 0, A.length-1);
}
public static boolean isValidPreorderBST(int[] A, int start, int end) {
	if(start >= end) return true;
	int i=start+1;
	for(; i<=end; i++) {
		if(A[i] > A[start]) break;
	}
	int j = i;
	while(j <= end) {
		if(A[j++] <= A[start]) return false;
	}
	return isValidPreorderBST(A, start+1, i-1) && isValidPreorderBST(A, i, end);
}

public static void main(String[] args) {
	String[] cases = new String[]{"1 2 3", "2 1 3", "3 2 1 5 4 6", "1 3 4 2", "3 4 5 1 2"};
	for(String s:cases) {
		String[] nums = s.split("\\s");
		int[] A = new int[nums.length];
		for(int i=0; i<A.length; i++) {
			A[i] = Integer.parseInt(nums[i]);
		}
		System.out.println(isValidPreorderBST(A));
	}
	
}

 

重构了一下,添加了min数组,保存从当前位置往后的最小值,省去了继续搜索比根节点值小的元素的时间。

public static boolean isValidPreorderBST(int[] A) {
	int n = A.length;
	if(n <= 1) return true;
	int[] min = new int[n];
	min[n-1] = A[n-1];
	for(int i=n-2; i>=0; i--) {
		min[i] = Math.min(min[i+1], A[i]);
	}
	return isValidPreorderBST(A, min, 0, n-1);
}
private static boolean isValidPreorderBST(int[] A, int[] min, int start, int end) {
	if(start >= end) return true;
	int i=start+1;
	for(; i<=end; i++) {
		if(A[i] > A[start]) break;
	}
	if(i<end && min[i+1] <= A[start]) return false;
	return isValidPreorderBST(A, min, start+1, i-1) && isValidPreorderBST(A, min, i, end);
}

 

以上解法的时间复杂度都是O(N^2)。

以下链接提供了O(N)的解法。

http://www.geeksforgeeks.org/construct-bst-from-given-preorder-traversa/

分享到:
评论

相关推荐

    End-to-end Sequence Labeling via Bi-directional LSTM-CNNs-CRF

    specific knowledge in the form of hand-crafted features and data pre-processing.In this paper, we introduce a novel neu-tral network architecture that benefits from both word- and character-level ...

    Content-based-Image-Retrieval.rar_After Method

    After pre-processing and segmentation of the input image, a local approach is used, where features are calculated for individual characters. The method is based on eigenimages calculated from edge &#...

    A.Collection.of.Bit.Programming.Interview.Questions.solved.in.C++

    Bits is the second of a series of 25 Chapters devoted to algorithms, problem solving, and C++ programming. This book is about low level bit programming Table of Contents Chapter 1. Given an unsigned ...

    查壳脱壳工具ACKiller 0[1][1].31 pre-release

    ACKiller 0[1][1].31 pre-releaseACKiller 0[1][1].31 pre-releaseACKiller 0[1][1].31 pre-releaseThe file userdb.txt is used to store the external signatures. ;External signatures can be modified by the ...

    a project model for the FreeBSD Project.7z

    Such an output can either be an input to another activity or a part of the process' delivery. 2.2. Process A “process” is a series of activities that lead towards a particular outcome. A process ...

    Graph-Based Semi-Supervised Learning

    line of work, researchers have started to realize that graphs provide a natural way to represent data in a variety of domains. Graph-based SSL algorithms, which bring together these two lines of work,...

    Building a Fine-Grained Entity Typing System Overnight for a New X

    Most existing methods require pre-defining a set of types and training a multi-class classifier from a large labeled data set based on multi-level linguistic features. They are thus limited to ...

    Lerner -- Python Workout. 50 Essential Exercises -- 2020.pdf

    - **Objective:** Create a function that can sum any type of iterable (e.g., list, tuple). - **Key Concepts:** - Using the `*args` parameter to accept variable arguments. - Type checking to ensure ...

    DNN-HMM Based Multilingual Recognizer of Telephone Speech

    Because the SAMPA with unnormalized convention is used to represent the phonetic content of the particular languages and different symbols are in several cases representing the same phone, the ...

    块方向追踪

    derived from the target model and the candidate model can represent the possibility that a pixel belongs to the target, we show that the original mean shift tracking algorithm can be derived using the...

    zigbee2007-协议英文

    The questions in a proforma consist of a systematic list of protocol capabilities and options as well as their implementation requirements. The implementation requirement indicates whether ...

    Machine Learning for Model Order Reduction

    This method is called model order reduction (MOR), which reduces the complexity of the original large system and generates a reduced-order model (ROM) to represent the original one. Readers will gain...

    A 3D Modeller-Erick Dransch.zip

    At their core, CAD tools are a method of abstracting the 3-dimensional design into something that can be viewed and edited on a 2-dimensional screen. To fulfill that definition, CAD tools must offer ...

    3D Object Detection with Latent Support Surfaces

    within 3D object categories can be explained by the location of a latent support surface, and smaller objects are often supported by larger objects. Therefore, we explicitly use latent support ...

    ehlib_vcl_src_9_3.26

    property for automatic filling a list in DropDownBox of the subtitle filter cell. TDataDriverEh component carry out two tasks: Delivers data to TMemTableEh. Processes changed records of ...

    Deep_Learning_Architecture_for_AI.pdf

    plicated functions that can represent high-level abstractions (e.g., in vision, language, and other AI-level tasks), one may need deep architec- tures. Deep architectures are composed of multiple ...

    i-vector的工具箱

    In order to better support interactive or batch usage, most of the tools in the Identity Toolbox accept either floating point or string arguments. String arguments, either for a file name or a ...

    Introduction to iUMLite 2.20

    - Specify the order and timing of events. #### Static Modeling of Domains Static modeling is represented on class diagrams, enhanced with supportive descriptions and data definitions. This type of ...

Global site tag (gtag.js) - Google Analytics