algorithm - 计算树中根左侧的节点数的函数
问题描述
如何计算根节点左侧的节点?这与计算树中的所有左节点不同。
解决方案
您应该通过跟踪根与所有其他节点之间的水平距离来计算根左侧的节点。按顺序遍历树并记住当前位置(如果您向左移动,则 +1,如果向右移动,则 -1)应该足以完成这项工作。
def count_left(tree, current_position):
if tree is None:
return 0
is_left = 1 if current_position > 0 else 0
return is_left + count_left(tree.right, current_position -1) + count_left(tree.left, current_position +1)
count_left(tree.left, 1)
推荐阅读
- python - 如何在 python 的程序退出上运行协程函数?
- javascript - XMPP 聊天架构
- sql - 如果键重复,则返回最长的字符串
- python - 使用for循环python遍历数组名称
- sql - 板条箱中的大规模更新
- javascript - React Native createDrawerNavigator 未打开导航抽屉
- reactjs - 反应不呈现列表元素
- javascript - 在这个 reduce 方法的末尾添加括号的目的是什么?
- php - 当我尝试发送邮件时,laravel 中的未定义变量
- flutter - Iconbuttons onTap 方法或任何其他 onTap 不能在颤动的堆栈小部件中工作吗?