剑指offer 二叉树的深度

二叉树的深度

题目

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

方法

方法1:递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# -*- 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

left_height=self.TreeDepth(pRoot.left)
right_height=self.TreeDepth(pRoot.right)
return 1+max(left_height,right_height)

方法2:非递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# -*- 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
stack=[(pRoot,1)]
depth=1
while stack:
node,cur_depth=stack.pop()

depth=max(depth,cur_depth)
if node.left:
stack.append((node.left,cur_depth+1))

if node.right:
stack.append((node.right,cur_depth+1))
return depth
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# -*- 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
stack=[(pRoot,1)]
depth=1
while stack:
node,cur_depth=stack.pop(0)
if node:
depth=max(depth,cur_depth)
stack.append((node.left,cur_depth+1))
stack.append((node.right,cur_depth+1))
return depth