题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
思路:
第一是我们可以通过借助一个队列进行层次遍历
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def TreeDepth(self, pRoot):
# write code here
if not pRoot:
return 0
dequ = []
dequ.append(pRoot)
nums = 0
while dequ:
res = []
for i in range(len(dequ)):
root = dequ.pop(0)
if root.left is not None:
dequ.append(root.left)
if root.right is not None:
dequ.append(root.right)
res.append(root.val)
if res:
nums+=1
return nums
第二是可以通过递归的方式求深度
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def TreeDepth(self, pRoot):
# write code here
if not pRoot:
return 0
return max(self.TreeDepth(pRoot.left),self.TreeDepth(pRoot.right))+1