首页 > 其他 > 详细

【leetcode - 94,144,145】前中后序遍历

时间:2020-04-09 14:07:07      阅读:66      评论:0      收藏:0      [点我收藏+]

 技术分享图片

【先序遍历】

思路: 根-左-右   1-2-4-5-6-3  遍历左树,直到节点的左孩子不存在,返回上一节点,走向右侧。

技术分享图片
class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        stack = []
        res = []
        cur = root
        while cur or stack:
            while cur:
                stack.append(cur)
                res.append(cur.val)
                cur = cur.left
            top = stack.pop()
            cur = top.right
        return res
前序迭代
技术分享图片
class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        res = []
        def helper(root):
            if not root:
                return 
            res.append(root.val)
            helper(root.left)
            helper(root.right)
        helper(root)
        return res
前序递归

【后序遍历】

思路: 左-右-根    4-6-5-2-3-1  考虑先序遍历,根-左-右,将后序遍历结果反过来得到:根-右-左,故按照先序的方法,将最终结果转换就可以了。

技术分享图片
class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        stack = []
        res = []
        cur = root
        while stack or cur:
            while cur:
                stack.append(cur)
                res.append(cur.val)
                cur = cur.right
            top = stack.pop()
            cur = top.left
        return res[::-1]
后序迭代
技术分享图片
class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        res = []
        def helper(root):
            if not root:
                return 
            helper(root.left)
            helper(root.right)
            res.append(root.val)
        helper(root)
        return res        
后序递归

【中序遍历】

思路: 左-根-右 4-2-5-6-1-3   考虑遍历的时候结果的list不添加值,在遍历到cur为空时再添加值

技术分享图片
class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        stack = []
        res = []
        cur = root
        while cur and stack:
            while cur:
                stack.append(cur)
                cur = cur.left
            top = stack.pop()
            res.append(top.val)
            cur = top.right
        return res
中序迭代
技术分享图片
class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        res = []
        def helper(root):
            if not root:
                return 
            helper(root.left)
            res.append(root.val)
            helper(root.right)
        helper(root)
        return res    
序递归

 

【leetcode - 94,144,145】前中后序遍历

原文:https://www.cnblogs.com/akassy/p/12666479.html

(1)
(1)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!