二叉树的先序中序后序遍历(非递归)
程序员文章站
2022-06-17 17:36:08
...
来自牛客网直通BAT算法精讲:
弹出栈顶并打印,先压右后压左
- def preOrder(self):
- if not self.root:
- return
- stackNode = []
- stackNode.append(self.root)
- while stackNode:
- node = stackNode.pop()
- print node.value,
- if node.rightNode:
- stackNode.append(node.rightNode)
- if node.leftNode:
- stackNode.append(node.leftNode)
- def midOrder(self):
- if not self.root:
- return
- stackNode = []
- node = None
- node = self.root
- while stackNode or node:
- while node:
- stackNode.append(node)
- node = node.leftNode
- node = stackNode.pop()
- print node.value,
- node = node.rightNode
def afterOrder(self,root):
stk1=[]
stk2=[]
stk1.append(root)
while stk1:
node=stk1.pop()
stk2.append(node)
stk1.append(node.lchild)
stk1.append(node.rchild)
while stk2:
print(stk2.pop())
def afterOrder2(self,root):
stk=[]
stk.append(root)
h=root
c=None
while stk:
c=stk[-1]
if c.lchid!=None and h!=c.lchid and H!=c.rchid:
stk.append(c.lcihld)
elif c.rchid!=0 and h!=c.rchild:
stk.append(c.rchid)
else:
node=stk.pop()
print(node)
上一篇: 我加入 MySQL 的 5 年时间