题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
分治法简介:求一个规模为n的问题,先求左边规模大约为n/2的问题,再求右边规模大约为n/2的问题,然后合并左边,右边的解,从而求得最终解。具体可参考归并排序。
步骤:
- 求 pro(left, rigth) -> int
- 先求pro(left, (left+right)/2) -> lval
- 再求pro((left+right)/2 + 1, right) -> rval
- merge(lval, rval) -> result
# -*- 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
depth_l = self.TreeDepth(pRoot.left)
depth_r = self.TreeDepth(pRoot.right)
return max(depth_l,depth_r)+1
层次遍历
# -*- 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
queue = []
queue.append(pRoot)
count = 0
while queue:
lens = len(queue)
while lens:
temp = queue.pop(0)
if temp.left:
queue.append(temp.left)
if temp.right:
queue.append(temp.right)
lens -= 1
count += 1
return count