转码艺术生,小白刷题练手,有些是讨论里面觉得解法不错的,轻喷。
剑指Offer
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
递归方法:
class Solution:
def TreeDepth(self, pRoot):
# write code here
if pRoot ==None:
return 0
lheight = 0
rheight = 0
if pRoot.right != None:
rheight = self.TreeDepth(pRoot.right)
if pRoot.left != None:
lheight = self.TreeDepth(pRoot.left)
if lheight> rheight:
return lheight+1
else:
return rheight+1
class Solution:
#不用递归方法,改用层次遍历
def TreeDepth(self, pRoot):
# write code here
if pRoot is None:
return 0
count = 0
q = []
q.append(pRoot)
while len(q)!=0:
#the number of nodes in each level
number = len(q) #这一层里所有的节点数
for i in range(number):
r = q.pop(0)
if r.right != None:
q.append(r.right)
if r.left != None:
q.append(r.left)
count = count+1
return count
这道题恶心的地方在于Python 2.7.3 不允许用count++
还是我资历太浅啊。