算法题,进链接看文本,不限语言c/c++/python,会的留下代码
问题描述:
链接: https://pan.baidu.com/s/10_s59j-1FOW9jGyYeYFaWg
提取码: 3fbd
答
# 定义节点类
class Node(object):
def __init__(self,val,left=None,right=None):
self.val = val
self.left = left
self.right = right
def BFS(root):
# 使用列表作为队列
queue = []
# 将首个根节点添加到队列中
queue.append(root)
# 当队列不为空时进行遍历
while queue:
# 从队列头部取出一个节点并判断其是否有左右节点
# 若有子节点则把对应子节点添加到队列中,且优先判断左节点
temp = queue.pop(0)
left = temp.left
right = temp.right
if left:
queue.append(left)
if right:
queue.append(right)
print(temp.val,end=" ")
答
用的dfs,你看下有没有问题。
#树节点
class Node(object):
def __init__(self,e=None,lchild=None,rchild=None):
self.data=e
self.lchild=lchild
self.rchild=rchild
#DFS
#root为树的根节点
class MaxLength:
def diameterOfBTree(self, root):
self.res = 0
def maxDiameter(root):
if not root:
return 0
l = maxDiameter(root.left)
r = maxDiameter(root.right)
self.res = max(self.res, l + r)
return max(l, r) + 1
maxDiameter(root)
return self.res