剑指Offer(Python多种思路实现):二叉树的深度
面试55题:
题目:二叉树的深度
题:输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
解题思路一:
①如果一棵树只有一个节点,它的深度为1
②如果根节点只有左子树而没有右子树,那么树的深度是左子树的深度加1
同样,如果根节点只有右子树而没有左子树,那么树的深度是右子树的深度加1
既有右子树又有左子树时,数的深度是左子树和右子树深度较大者加1
class Solution:
def TreeDepth(self, pRoot):
# write code here
if pRoot is None:
return 0
left = self.TreeDepth(pRoot.left)
right = self.TreeDepth(pRoot.right)
return max(left,right)+1
解题思路二:迭代
def maxDepth(self, root: 'TreeNode') -> 'int':
q = root and collections.deque([(root, 1)])
d = 0
while q:
node, d = q.popleft()
if node.right:
q.append((node.right, d+1))
if node.left:
q.append((node.left, d+1))
return d