# 确定二叉树的深度值,(python法)
# 阿里第二轮面试题(递归法)
class Treenode:
def __init__(self,x):
self.val = x
self.left = None
self.right = None
class Solution:
def finddepth(self,phead):
if phead == None:
return 0
else:
# 递归寻找
return max(1+self.finddepth(phead.left),1+self.finddepth(phead.right))
a1 = Treenode(1)
a2 = Treenode(2)
a3 = Treenode(4)
a4 = Treenode(3)
a5 = Treenode(5)
a1.left = a2
a1.right = a3
a2.left = a4
a2.right = a5
S = Solution()
S.finddepth(a1)
# 确定二叉树的深度值,(python法)
# 阿里第二轮面试题(非递归法)
class Treenode:
def __init__(self,x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.X = []# 储存遍历的节点
self.Y = []# 储存每层的一个节点值
def finddepth(self,phead):
if phead == None:
return 0
else:
self.X.append(phead)
return self.find(self.X)
def find(self,X):
i = 1 # 当前层节点数量
while len(X) != 0:
j = 0 # 统计下一层节点数量
while i > 0:
# 提取该层的节点
node = X.pop(0)
if i == 1:
# 在该层提取一个节点
self.Y.append(node.val)
if node.left != None:
# 添加下一层节点
X.append(node.left)
j += 1
if node.right != None:
# 添加下一层节点
X.append(node.right)
j += 1
i -= 1
i = j
return len(self.Y)
a1 = Treenode(1)
a2 = Treenode(2)
a3 = Treenode(3)
a4 = Treenode(4)
a5 = Treenode(5)
a1.left = a2
a1.right = a3
a2.left = a4
a2.right = a5
S = Solution()
S.finddepth(a1)