python - 没有节点与其子节点具有相同的颜色 - 递归
问题描述
给出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
问题是我不知道如何在这里调用递归。
解决方案
我可以填写您缺少的与递归有关的一些部分,但其他部分我将保留为您的原始伪代码作为练习。
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)
这里的递归部分是:
- Where
checkTree(n)
被调用,它沿着树的一条腿递归。 - final
return True
终止递归。
另外,这两个return False
语句是优化,当树明显不满足条件时避免整条腿。
推荐阅读
- ios - 如何在 Swift 的多个视图中使用一个活动指示器?
- latex - 我的 LaTex 参考书目对条目进行了两次编号,我不知道为什么
- javascript - 尝试使用 Firebase 存储和 Firestore 数据库上传图片 - 遇到地图错误
- reactjs - 替换目标时停止 mouseenter 触发
- linux - 有什么方法可以将此代码转换为在 Powershell 中工作?Strapi 需要部署到 Heroku
- javascript - 转换 JSON 表单前端,使其符合 API 的预期
- java - 在 Kubernetes 中运行 Mysql 时访问被拒绝
- python - 为什么在两个相似的 DataFrame 上切片工作不同?
- javascript - 在 Chart.js 3.5.0 中隐藏 y 轴上的标签无法正常工作
- wordpress - 控制台浏览器说它找不到我的主机上不存在的请求图像