LeetCode-3(非递归前中后序遍历)

来源:互联网 发布:淘宝上买steam游戏商家 编辑:程序博客网 时间:2024/05/20 16:14

一、Binary Tree Preorder Traversal

前序遍历(根 左 右),不使用递归
stack开始压入根,每次循环弹出stack最后一个节点p,
若p不为None
res记录值,stack依次压入p的右节点、左节点

class Solution(object):    def preorderTraversal(self, root):        """        :type root: TreeNode        :rtype: List[int]        """    res=[]        stack=[]        while stack or root:            if root:                stack.append(root)                res.append(root.val)                root=root.left            else:                root=stack.pop()                root=root.right                   return res   ################################################################        res=[]        stack=[root]        while stack:            cur=stack.pop()            if cur:                res.append(cur.val)                stack.append(cur.right)                stack.append(cur.left)        return res  

二、Binary Tree Postorder Traversal

后序遍历(左 右 根),不使用递归

前序遍历改造, 根左右 => 根右左(反转)=> 左右根

class Solution(object):    def postorderTraversal(self, root):        """        :type root: TreeNode        :rtype: List[int]        """        res=[]        stack=[]        while stack or root:            if root:                stack.append(root)                res.insert(0,root.val)                root=root.right            else:                root=stack.pop()                root=root.left        return res#######################################################        res=[]        stack=[root]        while stack:            cur=stack.pop()            if cur:                res.append(cur.val)                stack.append(cur.left)                stack.append(cur.right)        return res[::-1]  

三、Binary Tree Inorder Traversal

中序遍历(左 根 右),不使用递归

class Solution(object):    def inorderTraversal(self, root):        """        :type root: TreeNode        :rtype: List[int]        """        res=[]        stack=[]        while root or stack:            if root:                stack.append(root)                root=root.left            else:                root=stack.pop()                res.append(root.val)                root=root.right        return res
阅读全文
0 0