Title:
Given a binary tree, find its minimum depth.The minimum depth is the
number of nodes along the shortest path from the root node down to the
nearest leaf node.
Analysis:
Find the depth of the root node of a binary tree from the nearest leaf node
1. Judge whether the left and right subtrees of the current node are empty
2. If the left and right subtrees are empty, the return value is 1
3. If the left sub tree is empty and the right sub tree is not empty, the depth value of the right sub node of the current node + 1 will be returned
4. If the right sub tree is empty and the left sub tree is not empty, the depth value of the left sub node of the current node + 1 will be returned
5. If the left and right subtrees are not empty, the smaller value + 1 of the depth value of the left and right subtrees of the current node will be returned
Code:
def mindepth(root): tmp = root if(tmp.left == None and tmp.right == None): return 1 elif(tmp.left == None): return mindepth(tmp.right) + 1 elif(tmp.right == None): return mindepth(tmp.left) + 1 else: return(1+min(mindepth(tmp.left),mindepth(tmp.right)))
All codes:
class treenode : def __init__(self,val = None,left = None,right = None): self.val = val self.left = left self.right = right def settag(self,tag = None): self.tag = tag def insertnode(root,treenode): tmp = root if (root == None): root = treenode while(tmp != None): if(treenode.val == tmp.val): break elif(treenode.val <= tmp.val): if(tmp.left != None): tmp = tmp.left else: tmp.left = treenode else: if(tmp.right != None): tmp = tmp.right else: tmp.right = treenode return root def mindepth(root): tmp = root if(tmp.left == None and tmp.right == None): return 1 elif(tmp.left == None): return mindepth(tmp.right) + 1 elif(tmp.right == None): return mindepth(tmp.left) + 1 else: return(1+min(mindepth(tmp.left),mindepth(tmp.right))) if __name__=='__main__': t=treenode() L = [8,3,9,2,12,5,34,23,10] t.val = L[0] for x in L: node = treenode() node.val = x t = insertnode(t,node) print(mindepth(t)) print(maxdepth(t))