-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path7_1.py
82 lines (75 loc) · 2.08 KB
/
7_1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import math
class BiTNode:
def __init__(self):
self.data = None
self.lchild = None
self.rchild = None
class Stack:
#模拟栈
def __init__(self):
self.items=[]
#判断栈是否为空
def isEmpty(self):
return len(self.items)==0
#返回栈的大小
def size(self):
return len(self.items)
#返回栈顶元素
def top(self):
if not self.isEmpty():
return self.items[len(self.items)-1]
else:
return None
#弹栈
def pop(self):
if len(self.items)>0:
return self.items.pop()
else:
print(u"栈已经为空")
return None
#压栈
def push(self,item):
self.items.append(item)
def array2tree(arr,start,end):
root = None
if end >= start:
root = BiTNode()
mid = math.floor((start + end +1)/2)
root.data = arr[mid]
root.lchild = array2tree(arr,start,mid-1)
root.rchild = array2tree(arr,mid+1,end)
else:
root =None
return root
def getPathFromRoot(root,node,path_stack):
if root == node:
path_stack.push(root)
return True
if root == None:
return False
if getPathFromRoot(root.lchild,node,path_stack) or getPathFromRoot(root.rchild,node,path_stack):
path_stack.push(root)
return True
else:
return False
def findParentNode(root,node1,node2):
stack1 = Stack()
stack2 = Stack()
getPathFromRoot(root,node1,stack1)
getPathFromRoot(root,node2,stack2)
parent = None
while stack1.top() == stack2.top():
parent = stack1.top()
stack1.pop()
stack2.pop()
return parent
if __name__ == "__main__":
arr =[1,2,3,4,5,6,7,8,9,10]
root = array2tree(arr,0,len(arr)-1)
node1 = root.lchild.lchild.lchild
node2 = root.rchild
parent = findParentNode(root,node1,node2)
if parent != None:
print(str(node1.data) + u'和' + str(node2.data) + u'最近的公共父结点为'+ str(parent.data))
else:
print(u'没有公共结点')