# Leetcode (12) insert interval

Time：2022-8-2

#### Title:

Give a non overlapping interval list sorted by the beginning and end of the interval.

To insert a new interval into the list, you need to ensure that the intervals in the list are still orderly and do not overlap (you can merge the intervals if necessary).

#### Idea:

First, through analysis, we can find that there are three kinds of intervals. One is on the left side of the insertion interval, that is, the right interval is smaller than the left interval of the insertion interval. The other is on the right side of the insertion interval, that is, the left interval is larger than the right interval of the insertion interval. The above two kinds of intervals can be directly inserted into the new area, and the last one is the intersection with the insertion interval, which needs to be merged. Next is the code implementation: ``````func insert(intervals [][]int, newInterval []int) [][]int {
left,right := newInterval,newInterval
Var isinserted = false // used to determine whether the interval has been inserted. False means it has not been inserted, and true means it has been inserted
var ans [][]int
//1. Read the interval from left to right. If it does not intersect with the interval, insert it directly
//2. If it intersects with the interval, update the value of the interval and continue to judge
//3. If the reading is completed, or the first value that does not intersect with the interval is read, insert the interval
//4. Insert the new array directly into the inserted interval
for _,val := range intervals{
if isInserted{
ans = append(ans,val)
continue
}
if val>right && !isInserted{
ans = append(ans,[]int{left,right})
isInserted = true
ans = append(ans,val)
continue
}
if val<left && !isInserted{
ans = append(ans,val)
continue
}
left = min(left,val)
right = max(right,val)
}
if !isInserted{ans = append(ans,[]int{left,right})}
return ans
}
func max(x,y int)int{
if x>y{
return x
}
return y
}
func min(x,y int)int{
if x<y{
return x
}
return y
}`````` ## [NOIP2001 Popularization Group] Seek Ranking

Question analysis: The question mentions the pre-order, in-order, and post-order arrangement of trees, so we need to know what these three arrangements mean first. 3 (depth-first) permutations of binary trees: Pre-order, &quot;root left and right&quot;. That is, for each subtree of the binary tree, first visit its root, and then traverse its left and right […]