Merge Intervals
Total Accepted: 34742 Total Submissions: 155846My Submissions
Question Solution
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18]
,
return [1,6],[8,10],[15,18]
.
public class Solution {
TreeNode root;
List<Interval> z=new ArrayList<Interval>();
void InsertNode(Interval y){
TreeNode cur=root;
while(cur!=null)
{
int cur_s=cur.val.start;
int cur_e=cur.val.end;
if(cur_s>y.end)
{
if(cur.left==null)
{
TreeNode newnode=new TreeNode(y);
cur.left=newnode;
newnode.parent=cur;
break;
}
else
{
cur=cur.left;
}
}
else if(cur_e<y.start)
{
if(cur.right==null)
{
TreeNode newnode=new TreeNode(y);
cur.right=newnode;
newnode.parent=cur;
break;
}
else
{
cur=cur.right;
}
}
else
{
if(cur_s<=y.start&&cur_e>=y.end)
break;
else if(cur_s<=y.start&&cur_e<y.end)
{
//---------
//-----
cur.val.end=y.end;
while(cur.right!=null)
{
TreeNode p=cur.right;
while(p.left!=null)
{
p=p.left;
}
if(cur.val.end<p.val.start)
break;
else
{
if(p.parent.left==p)
{
p.parent.left=p.right;
if(p.right!=null)
p.right.parent=p.parent;
}
else
{
p.parent.right=p.right;
if(p.right!=null)
p.right.parent=p.parent;
}
if(p.val.end>cur.val.end)
cur.val.end=p.val.end;
}
}
break;
}
else if(cur_s>y.start&&cur_e>=y.end)
{
cur.val.start=y.start;
while(cur.left!=null)
{
TreeNode p=cur.left;
while(p.right!=null)
{
p=p.right;
}
if(cur.val.start>p.val.end)
break;
else
{
if(p.parent.left==p)
{
p.parent.left=p.left;
if(p.left!=null)
p.left.parent=p.parent;
}
else
{
p.parent.right=p.left;
if(p.left!=null)
p.left.parent=p.parent;
}
if(p.val.start<cur.val.start)
cur.val.start=p.val.start;
}
}
break;
}
else
{
cur.val.end=y.end;
while(cur.right!=null)
{
TreeNode p=cur.right;
while(p.left!=null)
{
p=p.left;
}
if(cur.val.end<p.val.start)
break;
else
{
if(p.parent.left==p)
{
p.parent.left=p.right;
if(p.right!=null)
p.right.parent=p.parent;
}
else
{
p.parent.right=p.right;
if(p.right!=null)
p.right.parent=p.parent;
}
if(p.val.end>cur.val.end)
cur.val.end=p.val.end;
}
}
cur.val.start=y.start;
while(cur.left!=null)
{
TreeNode p=cur.left;
while(p.right!=null)
{
p=p.right;
}
if(cur.val.start>p.val.end)
break;
else
{
if(p.parent.left==p)
{
p.parent.left=p.left;
if(p.left!=null)
p.left.parent=p.parent;
}
else
{
p.parent.right=p.left;
if(p.left!=null)
p.left.parent=p.parent;
}
if(p.val.start<cur.val.start)
cur.val.start=p.val.start;
}
}
break;
}
}
}
}
void GenerateTree(List<Interval> t){
for(int i=1;i<t.size();i++)
{
InsertNode(t.get(i));
}
}
void TravelTree(TreeNode h)
{
if(h!=null)
{
z.add(h.val);
TravelTree(h.left);
TravelTree(h.right);
}
}
public List<Interval> merge(List<Interval> intervals) {
int s=intervals.size();
if(s==0)
return z;
else if(s==1)
{
z.add(intervals.get(0));
return z;
}
else
{
root=new TreeNode(intervals.get(0));
GenerateTree(intervals);
TravelTree(root);
return z;
}
}
}
class TreeNode{
Interval val;
TreeNode left;
TreeNode right;
TreeNode parent;
TreeNode(Interval j){
val=j;
parent=null;
left=null;
right=null;
}
}