如何递归地找到二叉树中节点的高度 [英] how to find the height of a node in binary tree recursively
本文介绍了如何递归地找到二叉树中节点的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
path = 0 # the lenght of the path
while self.right != None or self.left != None:
while self.right != None:
self = self.right
path = path +1
while self.left != None:
self = self.left
path = path +1
return path
这是我用于查找高度的示例代码,定义为 从自身到叶子的节点数的最长路径.叶节点的高度为1.
this is my sample code for find the Height, is defined as the length of the longest path by number of nodes from self to a leaf. The height of a leaf node is 1.
它不起作用.
推荐答案
您正在做的事情不是递归的,而是迭代的. 递归类似于:
What you're doing isn't recursive, it's iterative. Recursive would be something like:
def height(node):
if node is None:
return 0
else:
return max(height(node.left), height(node.right)) + 1
这篇关于如何递归地找到二叉树中节点的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文