给定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
问题是我不知道如何在这里调用递归。
答案 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)
这里的递归部分是:
checkTree(n)
的地方,在那里追逐树的一条腿。return True
。另外,return False
个const 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}/>
});
语句是优化的,当树变得明显不符合条件时,它们可以避免整条腿。