二叉树非递归遍历

发布时间:2026/7/28 17:50:20
二叉树非递归遍历 defpre_order(root): 前序: 根 左 右 stack: 入栈顺序: 右 左 出栈顺序: 左 右 ifnotroot:return[]stack[]res[]stack.append(root)whilestack:rootstack.pop()res.append(root.val)ifroot.right:stack.append(root.right)ifroot.left:stack.append(root.left)returnresdefin_order(root): 中序: 左 根 右 stack root 不断压入左 没有左了 弹出一个根 看有没右节点 接着不断压入右节点的左 ifnotroot:return[]stack[]res[]whilestackorroot:ifroot:stack.append(root)rootroot.leftelse:rootstack.pop()res.append(root.val)rootroot.rightdefpost_order(root): 后序: 左 右 根 stack root stack: 压一个根 并 将其添加到res的队首 且 不断压入右 出一个 看左 ifnotroot:return[]stack[]res[]whilestackorroot:ifroot:stack.append(root)res.insert(0,root.val)rootroot.rightelse:rootstack.pop()rootroot.leftreturnresdefpost_order(root):ifnotroot:return[]stack[]res[]stack.append(root)whilestack:rootstack.pop()ifroot.left:stack.append(root.left)ifroot.right:stack.append(root.right)res.insert(0,root.val)returnres