博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【剑指offer】q50:树中结点的最近祖先
阅读量:4067 次
发布时间:2019-05-25

本文共 1603 字,大约阅读时间需要 5 分钟。

#@ root: the root of searched tree#@ nodeToFind: the tree-node to be found#@ path: the path from root to node#@@#@@ search tree referenced by root, and return the path #@@ from root to node, if node not exist, path = []#@@def getPath(root, nodeToFind, path):	if ( None == root or None == nodeToFind):		return False	# case 1: current root == node, so insert to path	if root == nodeToFind:		path.insert(0, root)		return True 	# search in left barch and right branch	bFindInLeft = False	bFindInRight = False	if root.left:		bFindInLeft = getPath(root.left, nodeToFind, path)	if False == bFindInLeft and root.right :		bFindInRight = getPath(root.right, nodeToFind, path)	# case 2: nodeToFind in subtree of root, insert root 	if bFindInLeft or bFindInRight:		path.insert(0, root)		return True	return False

函数的功能是在root 表示的树中查找nodeToFind 结点,若找到,则在返回的时候,将路径结点加入到path中,关于树的遍历有三种,这里我们使用后序遍历,目的是在知道所有情况后,再对root进行处理,因为当前的结点root应不应该加入到路径path中,不仅跟当前的结点root有关,还跟它的子结点有关,也就是若当前结点就是要找的结点,那么将当前结点加入是没有问题的,但是即使当前结点不是要查找的结点,而其子树中有查找结点时,当前结点也是要加入到路径中去的。这样就不用每次都将结点插入,条件不满足时还要进行结点的pop。

def getClosetParent(root, node1, node2):	path1 = []; path2 = []	if None == root or None == node1 or None == node2:		return None	#get the path from root to node1 and node2	getPath(root, node1, path1)	getPath(root, node2, path2)	# find closet parent of node1 and node2	shorPathLen = min( len(path1), len(path2) )	for i in range(1, shorPathLen):		if path1[ i ] != path2[ i ] and \			path1[ i - 1 ] == path2[ i - 1 ]:			return path1[ i - 1 ]	return None
因为在getPath函数里,我们获得的路径是从root开始的,即root为path列表的第一个结点,那么我们就从root开始,一次比较,找到最后一个相等的,就是二者最近的公共祖先。

转载地址:http://numji.baihongyu.com/

你可能感兴趣的文章
Linux +Win LAMPP Tools XAMPP 1.7.3 / 5.6.3
查看>>
my read_university
查看>>
network manager
查看>>
searchServer IBM OminiFind / WebSphere Commerce SOLR
查看>>
OS + Linux Disk disk lvm / disk partition / disk mount / disk io
查看>>
my read_Country
查看>>
RedHat + OS CPU、MEM、DISK
查看>>
project bbs_discuz
查看>>
net TCP/IP / TIME_WAIT / tcpip / iperf / cain
查看>>
Unix + OS books
查看>>
script webshell jspWebShell / pythonWebShell / phpWebShell
查看>>
project site_dns
查看>>
webServer kzserver/1.0.0
查看>>
hd printer lexmark / dazifuyin / dayin / fuyin
查看>>
OS + Unix IBM Aix basic / topas / nmon / filemon / vmstat / iostat / sysstat/sar
查看>>
monitorServer nagios / cacti / tivoli / zabbix / SaltStack
查看>>
my ReadMap subway / metro / map / ditie / gaotie / traffic / jiaotong
查看>>
OS + Linux DNS Server Bind
查看>>
web test flow
查看>>
web test LoadRunner SAP / java / Java Vuser / web_set_max_html_param_len
查看>>