求二叉树中最多的黑色节点

Problem: given a tree, color nodes black as many as possible without coloring two adjacent nodes

 

思路: 如果根节点r被标记为黑色,则其直接子节点不能被标记为黑色,如果不标记r,则其子节点可以标记为黑色,得到状态转移方程:

find(r) = max(black(r), white(r))

black(r)为当节点r被标记为黑色时,以r根节点的树中最多可标记为黑色的节点数

white(r)为当节点r不被标记为黑色时,以r根节点的树中最多可标记为黑色的节点数

white(r) = find(r.left) + find(r.right)  

//当r没被标记为黑色时,对其左右子节点继续寻找

 

black(r) = 1 + whilte(r.left) + white(r.right)

//当r被标记为黑色时,它自身对总黑色节点数贡献1,然后它的左右子节点一定是非黑色节点

 

 1 package com.self;
 2 
 3 public class DP_03_Tree {
 4 
 5     public static void main(String[] args) {
 6         
 7         Node node4 = new Node(4);
 8         Node node3 = new Node(3);
 9         Node node5 = new Node(5);
10         Node node2 = new Node(2);
11         Node node1 = new Node(1);
12         
13         node4.left = node3;
14         node4.right = node5;
15         node3.left = node2;
16         node3.right = node1;
17         
18         DP_03_Tree app = new DP_03_Tree();
19         int maxBlack = app.find(node4);
20         System.out.println(maxBlack);
21     }
22     
23     int find(Node node){
24         if(null == node) return 0;
25         if(null == node.left && null == node.right) return 1;
26         return Math.max(findFromWhite(node), findFromBlack(node));
27     }
28     
29     //Current node is white
30     int findFromWhite(Node node){
31         if(null == node) return 0;
32         return find(node.left)+find(node.right);
33     }
34     
35     //Current node is black
36     int findFromBlack(Node node){
37         if(null == node) return 0;
38         //Current node is black, then its children do not count, but itself counts
39         return 1 + findFromWhite(node.left) + findFromWhite(node.right);
40     }
41 }
42 
43 class Node{
44     int v;
45     Node left;
46     Node right;
47     Node(int v){
48         this.v = v;
49     }
50 }

 

转载于:https://www.cnblogs.com/aalex/p/4977951.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值