如何将斐波那契数列递归插入二叉树中
希望有人可以提供帮助,我不是程序员,但一直对探索斐波那契数列及其递归树感兴趣...
我创建了一个二叉树类以及关联的 TreeNode 类,并且想要生成一棵二叉树由以下方式创建的递归调用:
对于给定的 n 值,f(n) = f(n-1) + f(n-2)
我想将其添加为二叉树类的 InsertFibonacci 方法,替换标准 Insert 方法:
def insertNode(self, root, inputData):
if root == None:
return self.addNode(inputData)
else:
if inputData <= root.nodeData:
root.left = self.insertNode(root.left, inputData)
else:
root.right = self.insertNode(root.right, inputData)
return root
我会添加Fib 函数的某种装饰器?
# Fib function
def f(n):
def helper(n):
left = f(n-1)
right = f(n-2)
return left,right
if n == 0:
return 0
elif n == 1:
return 1
else:
left, right = helper(n)
return left + right
Hope someone can help, I'm not a programmer, but have been interested in exploring Fibonacci sequence and it's recursive tree...
I've created a Binary Tree class, along with an associated TreeNode class, and want to generate a binary tree of the recursive calls created by:
f(n) = f(n-1) + f(n-2) for a given value of n
I'd want to add it as an InsertFibonacci method of my Binary Tree class, replacing the standard Insert method:
def insertNode(self, root, inputData):
if root == None:
return self.addNode(inputData)
else:
if inputData <= root.nodeData:
root.left = self.insertNode(root.left, inputData)
else:
root.right = self.insertNode(root.right, inputData)
return root
Would I add somekind of decorator to the Fib function?
# Fib function
def f(n):
def helper(n):
left = f(n-1)
right = f(n-2)
return left,right
if n == 0:
return 0
elif n == 1:
return 1
else:
left, right = helper(n)
return left + right
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是我能想到的最简单的解决方案:
Here's the simplest solution I can think of:
这是一种方法:
假设
n
为正。应该返回斐波那契调用树的根。
请注意,这不会是完全相同类型的二叉树;它不能满足二叉搜索树所具有的排序不变性。我假设您只是想使用现有的结构以方便起见。
Here's one way:
Assumes positive
n
.Should return the root of the fibonacci call tree.
Note that this won't exactly be the same kind of binary tree; it won't satisfy the ordering invariant that a binary search tree does. I'm assuming you just want to use your existing structure for convenience.