二叉树面试问题1:计算一共有多少个节点。
'''算法思想:运用递归的思想,迭代计算出节点的个数。
遍历二叉树,分别计算左子树和右子树的节点个数,依次递归,最后返回左子树和右子树的总数和+1
'''
代码实现:
class Node(object):
'''节点类'''
def __init__(self, elem, lchild=None, rchild=None):
self.elem = elem
self.lchild = lchild
self.rchild = rchild
def TotalPoint(tree):
total = 0
if tree == None:
return 0
else:
total += 1
ltotal = TotalPoint(tree.lchild)
rtotal = TotalPoint(tree.rchild)
return ltotal + rtotal + 1
if __name__=='__main__':
tree = Node('D',Node('B',Node('A'),Node('C')),Node('E',rchild=Node('G',Node('F'))))
print(TotalPoint(tree))
二叉树面试问题2:计算二叉树的深度。
'''算法思想:通过递归的方式遍历二叉树,取左子树和右子树中最depth最大的值作为树的深度'''
代码实现:
class Node(object):
'''节点类'''
def __init__(self, elem, lchild=None, rchild=None):
self.elem = elem
self.lchild = lchild
self.rchild = rchild
def TreeDepth(tree):
depth = 0
if tree == None:
return 0
else:
depth += 1
ldepth = TreeDepth(tree.lchild)
rdepth = TreeDepth(tree.rchild)
if ldepth > rdepth:
return ldepth + 1
else:
return rdepth + 1
if __name__=='__main__':
tree = Node('D',Node('B',Node('A'),Node('C')),Node('E',rchild=Node('G',Node('F'))))
print(TreeDepth(tree))
二叉树面试问题3:三种遍历二叉树,先序遍历,中序遍历,后序遍历。都是运用的递归思想,经典的算法。
这个问题,在之前的博客中已经写过,不在重复,下面是链接
https://blog.youkuaiyun.com/sinceNow/article/details/90023146

本文探讨了二叉树的面试常见问题,包括计算二叉树的节点个数、深度,以及如何进行前序、中序、后序遍历。通过递归思想解析算法,帮助理解二叉树的基本操作。
517

被折叠的 条评论
为什么被折叠?



