没有节点与其子节点具有相同的颜色 - 递归

时间:2018-05-08 13:28:58

标签: python recursion tree

给定binary tree 2种颜色(green,red)决定给定树是否为Green-Red树。 Green-Red树的一个条件是:Each node has different color than its children

def checkTree(node):
    if node is None:
        return
    //return checkTree(node.left) and checkTree(node.right) - not sure about this 
    if node has 1 child:
        if they are same color:
            return False
        return True
    if node has 2 child:
        if left children or right children has same color as node:
            return False
        return True

问题是我不知道如何在这里调用递归。

1 个答案:

答案 0 :(得分:2)

我可以填写你遗漏的一些与递归有关的部分,但其他部分我将作为原始伪代码留作练习。

def checkTree(node):
    if node has no children:  # pseudo code, FIXME
        return True   # Terminate the recursion here

    if node has 1 child:
        if they are same color:
            return False
        return checkTree(singleChild)  # you need code that will find the child, FIXME
    if node has 2 children:
        if left children or right children has same color as node:
            return False
        return checkTree(node.left) and checkTree(node.right)

这里的递归部分是:

  1. 调用checkTree(n)的地方,在那里追逐树的一条腿。
  2. 终止递归的最终return True
  3. 另外,return Falseconst renderButtons = (actions: Interfaces.DeclarationAction[]) => actions.map((action, i) => { if (action.name === 4) { <Confirm name={modalName()} content="Are you sure?" onConfirm={checkingFinish} /> } <ActionButton key={i} action={action} onClickAction={props.onClickAction} declaration={props.declaration}/> }); 语句是优化的,当树变得明显不符合条件时,它们可以避免整条腿。