小算法题--5 三色二叉树

一棵二叉树可以按照如下规则表示成一个由0、1、2组成的字符序列,我们称之为“二叉树序列S”:

例如,下图所表示的二叉树可以用二叉树序列S=21200110来表示。

你的任务是要对一棵二叉树的节点进行染色。每个节点可以被染成红色、绿色或蓝色。并且,一个节点与其子节点的颜色必须不同,如果该节点有两个子节点,那么这两个子节点的颜色也必须不相同。给定一棵二叉树的二叉树序列,请求出这棵树中最多和最少有多少个点能够被染成绿色。

 

输入数据由多组数据组成。
每组数据仅有一行,不超过10000个字符,表示一个二叉树序列。

 

对于每组输入数据,输出仅一行包含两个整数,依次表示最多和最少有多少个点能够被染成绿色。

 

基本想法:对于root节点的每种染色方法,分别处理左右子树。

               对于左右子树,问题变为规模更小的同类问题。

               递归即得

 

class Node:
    def __init__(self,color=0,left=None,right=None):
        self.color=color
        self.left=left
        self.right=right

class Tree:
    def __init__(self,root=None):
        self.root=root



a=[1,1,2,2,0,0,2,0,1,0]
t=Tree()
t.root=Node()
stack=[t.root]

while len(a):
    n=a.pop(0)
    if n==2:
        p=stack.pop()
        p.left=Node()
        p.right=Node()
        stack.append(p.right)
        stack.append(p.left)
    elif n==1:
        p=stack.pop()
        p.left=Node()
        stack.append(p.left)
    else:
        stack.pop()

def ColorTree_Max(root_c,root):
    if root is None:
        return 0
    Max=0
    root.color=root_c
    if root_c==1:
        Max+=1
        Max+=max(ColorTree_Max(2,root.left)+ColorTree_Max(3,root.right),
             ColorTree_Max(3,root.left)+ColorTree_Max(2,root.right))
        return Max
    elif root_c==2:
        Max+=max(ColorTree_Max(1,root.left)+ColorTree_Max(3,root.right),
             ColorTree_Max(3,root.left)+ColorTree_Max(1,root.right))
        return Max
    else:
        Max+=max(ColorTree_Max(1,root.left)+ColorTree_Max(2,root.right),
             ColorTree_Max(2,root.left)+ColorTree_Max(1,root.right))
        return Max


def ColorTree_Min(root_c,root):
    if root is None:
        return 0
    Min=0
    root.color=root_c
    if root_c==1:
        Min+=1
        Min+=min(ColorTree_Min(2,root.left)+ColorTree_Min(3,root.right),
             ColorTree_Min(3,root.left)+ColorTree_Min(2,root.right))
        return Min
    elif root_c==2:
        Min+=min(ColorTree_Min(1,root.left)+ColorTree_Min(3,root.right),
             ColorTree_Min(3,root.left)+ColorTree_Min(1,root.right))
        return Min
    else:
        Min+=min(ColorTree_Min(1,root.left)+ColorTree_Min(2,root.right),
             ColorTree_Min(2,root.left)+ColorTree_Min(1,root.right))
        return Min

print max(ColorTree_Max(1,t.root),ColorTree_Max(2,t.root),ColorTree_Max(3,t.root))
print min(ColorTree_Min(1,t.root),ColorTree_Min(2,t.root),ColorTree_Min(3,t.root))
 
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值