我的思路是:
我们设立一个变量 储存当前最低的层数
同时为每颗子树,都定义一个标识符,告知这颗子树是否已找到最底层
根据先序遍历的顺序,并在遍历函数中传入所处深度
对每个节点的左右孩子进行考察
若发现一个节点的左右孩子都为空,则停止遍历,并比较这个节点的深度和 存储的变量谁小,保留最小的,并将这颗子树的标识符设为True
若这颗子树的标识符为False,我们对非空的左右孩子继续遍历
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.mindepth = None
def minDepth(self, root: TreeNode) -> int:
if root == None:
return 0
self.bianli(root,1,False)
return self.mindepth
def bianli(self,node,depth,thissub):
if node.left == None and node.right == None:
thissub = True
if self.mindepth == None:
self.mindepth = depth
else:
self.mindepth = min(self.mindepth,depth)
depth += 1
if thissub == False and node.left != None:
self.bianli(node.left,depth,False)
if thissub == False and node.right != None:
self.bianli(node.right,depth,False)