Maximum Depth of Binary Tree
Maximum Depth of Binary Tree
题目
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
思路
max(左分支高度,右分支高度)+1
队列,BFS
解题
c++版
1 | /** |
Python版1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return an integer
def maxDepth(self, root):
Depth=0
if not root:
return 0
queue=[]
queue.append(root)
count=len(queue)
while len(queue)!=0:
tmp=queue[0]
del queue[0]
count=count-1
if tmp.left:
queue.append(tmp.left)
if tmp.right:
queue.append(tmp.right)
if count==0:
Depth+=1
count=len(queue)
return Depth