Nine Chapters count judges Net-original website
http://www.jiuzhang.com/problem/42/
Topics
Given an array a without repeating elements, define the Maxtree on a as follows: the root node of Maxtree is the largest number in a, the left subtree of the root node is the largest number in the left part of the Maxtree, and the right subtree is the maxtree of the largest number in the right part of the array. Please design an algorithm to construct the maxtree of this array according to the given array A.
Answer
If you can determine the parent node of each node, you can construct the entire tree. Find out the number of the first number to the left and the first number to the right number, and the smaller number is the Father node of the number. such as: [3,1,2],3 No Father node, 1 fathers node for 2,2 Father's Day is 3. It is also possible to determine whether the left son or the right son is based on the position relationship with the father. The next question is how to quickly figure out the number of each number that goes to the left and to the right, the first one bigger than him. The data structure stack is needed here. For example, to find the first number on the left of each number is larger than his, from left to right to traverse each number, the stack is kept descending sequence, the new number of continuous pop out of the stack top until the top of the stack than the new number or no number. Take [3,1,2] For example, first 3 into the stack, the next 1:3 small, no pop out 3, 1 into the stack, and determined 1 to the left the first larger than his number is 3. Next 2:1 big, 1 out of the stack, 2:3 small, 2 into the stack. and determined 2 to the left the first one larger than his number is 3. The same method can be used to calculate the number of each number to the right of the first one larger than him. Time complexity O (n), spatial complexity is also O (n) is the optimal solution.
Interviewer Angle
First, it is easy to think of the use of recursive methods to construct maxtree, each layer recursively using O (n) to find the maximum number, and then divide the array into the left and right two parts, and then recursively complete the construction. This algorithm may be n^2 in extreme cases, so it cannot be accepted by the interviewer. But first you should at least answer this violent approach and analyze the worst-case complexity, as it will at least reflect some of your skills in algorithmic and time-complexity analysis. In case the right way behind is not answered, at least not 0 points. The stack method used by the optimal algorithm is a very common problem-solving technique. We will also be in the future interview questions for everyone to explain the topic of this approach.
Nine chapters algorithm surface question 42 construction Maxtree