找到二叉树中符合搜索二叉树条件的最大拓扑结构

找到二叉树中符合搜索二叉树条件的最大拓扑结构
给定一棵二叉树的头节点 head,已知所有节点的值都不一样,返回其中最大的、且符合搜索二叉树

条件的拓扑结构的节点数。这里的拓扑结构是指,你可以在二叉树中任意选择某些节点,只要这些节 点是连在一起的,都叫做二叉树的拓扑结构。

public static class Node{
	public int value;
	public Node right;
	public Node left;
	public Node(int data){
		this.value = data;
	}
}

public static int bstTopoSize1(Node head){
	if(head == null){
		return 0;
	}
	int max = maxTopo(head, head);
	max = Math.max(bstTopoSize1(head.left), max);
	max = Math.max(bstTopoSize1(head.right), max);
	return max;
}

public static int maxTopo(Node h, Node n){
	if(h != null && n != null && isBSTNode(h,n,n.value)){
		return maxTopo(h, n.left) + maxTopo(h, n.right) + 1;
	}
	return 0;
}

public static boolean isBSTNode(Node h, Node n, int value){
	if(h == null){
		return false;
	}
	if(h == n){
		return true;
	}
	return isBSTNode(h.value > h.left : h.right, n, value);
}

public static class Record{
	public int l;
	public int r;
	public Record(int left, int right){
		this.l = left;
		this.r = right;
	}
}

public static int bstTopoSize2(Node head){
	Map<Node, Record> map = new HashMap<Node, Record>();
	return posOrder(head, map);
}

public static int posOrder(Node h, Map<Node, Record> map){
	if(h == null){
		return 0;
	}
	int ls = posOrder(h.left, map);
	int rs = posOrder(h.right, map);
	modifyMap(h.left, h.value, map, true);
	modifyMap(h.right, h.value, map, false);
	Record lr = map.get(h.left);
	Record rr = map.get(h.right);
	int lbst = lr = null ? 0 : lr.l + lr.r + 1;
	int rbst = rr = null ? 0 : rr.l + rr.r + 1;
	map.put(h, new Record(lbst, rbst));
	return Math.max(lbst + rbst + 1, Math.max(ls, rs));
}

public static int modifyMap(Node n, int v, Map<Node, Record> m, boolean s){
	if(n == null || (!m.containsKey(n))){
		return 0;
	}
	Record r = m.get(n);
	if((s && n.value > v) || ((!s) && n.value < v)){
		m.remove(n);
		return r.l + r.r + 1;
	}else{
		int minus = modifyMap(s ? n.right, v, m, s);
		if(s){
			r.r = r.r - minus;
		}else{
			r.l = r.l - minus;
		}
		m.put(n, r);
		return minus;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值