@@ -111,10 +111,108 @@ def dfs_travel_postorder(self, node):
111111 print (node .data , end = ' ' )
112112
113113
114+ class BinTreeStack :
115+ """
116+ 使用栈模拟二叉树
117+ 栈:后进先出(LIFO)
118+ """
119+
120+ def __init__ (self , root = None ):
121+ # super().__init__(root) # python3
122+ # super(BinTreeStack, self).__init__(root) # python2
123+ self .root = root
124+ self .stack = []
125+
126+ def make_tree (self , tree , val ):
127+ if val is None :
128+ return
129+ else :
130+ tree .data = val
131+ tree .left_subtree = Node (val )
132+ self .make_tree (tree .left_subtree , val )
133+ tree .right_subtree = Node (val )
134+ self .make_tree (tree .right_subtree , val )
135+
136+ def dfs_travel_stack_preorder (self , tree ):
137+ """
138+ 栈的方式前序遍历
139+ 先把根节点入栈,然后左节点,最后右节点
140+ :return:
141+ """
142+ if self .root is None :
143+ return
144+ stack = []
145+ node = tree
146+ while node or stack :
147+ while node :
148+ print (node .data )
149+ stack .append (node )
150+ node = node .left_subtree
151+ node = stack .pop ()
152+ node = node .right_subtree
153+
154+ def dfs_travel_stack_inorder (self , tree ):
155+ """
156+ 以栈的方式中序遍历 左 -> 根 -> 右
157+ :param tree:
158+ :return:
159+ """
160+ if self .root is None :
161+ return
162+ stack = []
163+ node = tree
164+ while node or stack :
165+ stack .append (node )
166+ node = node .left_subtree
167+ node = stack .pop ()
168+ print (node .data )
169+ node = node .right_subtree
170+
171+ def dfs_travel_stack_postorder (self , tree ):
172+ if self .root is None :
173+ return
174+ stack_1 = []
175+ stack_2 = []
176+ node = tree
177+ stack_1 .append (node )
178+ while stack_1 :
179+ node = stack_1 .pop ()
180+ if node .left_subtree :
181+ stack_1 .append (node .left_subtree )
182+ if node .right_subtree :
183+ stack_1 .append (node .right_subtree )
184+ stack_2 .append (node )
185+ while stack_2 :
186+ node = stack_2 .pop ()
187+ print (node .data )
188+
189+
114190if __name__ == '__main__' :
115191 t = BinTree ()
116192 for i in range (10 ):
117- t .add_node (1 )
193+ t .add_node (i )
194+
195+ print ('bfs_travel:' )
118196 t .bfs_travel ()
119- print ('bfs_travel' )
120- t .dfs_travel_preorder ()
197+ print ('\n dfs_travel_preorder:' )
198+ t .dfs_travel_preorder (t .root )
199+ print ('\n dfs_travel_inorder:' )
200+ t .dfs_travel_inorder (t .root )
201+ print ('\n dfs_travel_postorder:' )
202+ t .dfs_travel_postorder (t .root )
203+ '''
204+ bfs_travel:
205+ 0 1 2 3 4 5 6 7 8 9
206+ dfs_travel_preorder:
207+ 0 1 3 7 8 4 9 2 5 6
208+ dfs_travel_inorder:
209+ 7 3 8 1 9 4 0 5 2 6
210+ dfs_travel_postorder:
211+ 7 8 3 9 4 1 5 6 2 0
212+ '''
213+ print ('*' * 20 , end = '\n ' )
214+ # st = BinTreeStack()
215+ # for i in range(10):
216+ # st.make_tree(st, i)
217+ # st.dfs_travel_stack_preorder(st)
218+ # # st.dfs_travel_stack_inorder(st.root)
0 commit comments