deftraversal(root): # 中序遍历的非递归形式 stack = [] cur = root while cur isnotNoneor stack: while cur isnotNone: stack.append(cur) cur = cur.left cur = stack.pop() # 直接yield当前node yield cur cur = cur.right
通过代码来阐述具体思路。
1 2 3 4 5 6 7 8 9 10
deftree_to_sorted_list(root): node_iter = root.inorder_traverse() p_node = next(node_iter) head = p_node for node in node_iter: p_node.right = node p_node.left = None node.left = p_node p_node = node return head