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

 

【先序遍历】

思路: 根-左-右   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    
序递归

 

posted @ 2020-04-09 13:51  Akassy  阅读(172)  评论(0)    收藏  举报