题目描述
求给定二叉树的最小深度。最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量。
1(最初劣质版)
思路
遍历所有从根节点到叶子节点的路径,求最短
- 当栈顶左子树右子树均为空时→叶子节点:如果长度小于最短长度则记为最短长度,否则退回父节点,并进入废弃数组
- 当栈顶左子树不为空且左儿子不在废弃数组:左儿子入栈
- 当栈顶右子树不为空且右儿子不在废弃数组:右儿子入栈
- 当栈顶左子树右子树均不为空但均在废弃数组时:出栈
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
#
# @param root TreeNode类
# @return int整型
#
class Solution:
def run(self , root):
# write code here
if not root:
return 0
pstack = [root]
used = []
result = -1
while pstack:
if pstack[-1].left==None and pstack[-1].right==None:#leaf
if len(pstack) < result or result==-1:
result = len(pstack)
tmp = pstack.pop(-1)
used.append(tmp)#del
elif pstack[-1].left is not None and pstack[-1].left not in used:
pstack.append(pstack[-1].left)
elif pstack[-1].right is not None and pstack[-1].right not in used:
pstack.append(pstack[-1].right)
else:
tmp = pstack.pop(-1)
used.append(tmp)#del
return result
2(层次遍历)
思路
层次遍历,遇见第一个叶子节点则返回当前深度
def run(self , root ):
# write code here
if not root:
return 0
level = [root]
result = 0
tmp = []
while level:
i = level.pop(0)
if not i.left and not i.right:
result += 1
return result
else:
if i.left:
tmp.append(i.left)
if i.right:
tmp.append(i.right)
if not level:
level = tmp.copy()
result += 1
tmp = []
return result-1
3(借鉴其他大佬)
def run2(self , root ):
# write code here
if not root:
return 0
queue, min_depth = [root], 1
while queue:
temp = []
for node in queue:
if not node.left and not node.right:
return min_depth
if node.left:
temp.append(node.left)
if node.right:
temp.append(node.right)
queue = temp
min_depth += 1