Leetcode DAY14: 递归遍历 and 迭代遍历 and 统一迭代

一、递归遍历

(1)前序遍历

class Solution:
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        
        def Traversal(cur: Optional[TreeNode], tmp: List[int]):

            if not cur: return
            #中 左 右
            tmp.append(cur.val)
            Traversal(cur.left, tmp)
            Traversal(cur.right, tmp)
        
        res = []
        Traversal(root, res)
        return res

(2)中序遍历

class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        def Traversal(cur: Optional[TreeNode], tmp: List[int]):
            if not cur: return
            Traversal(cur.left, tmp)
            tmp.append(cur.val)
            Traversal(cur.right, tmp)

        res = []
        Traversal(root, res)
        return res

(3)后序遍历

class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:

        def Traversal(cur: Optional[TreeNode], tmp: List[int]):
            if not cur: return
            #左右中
            Traversal(cur.left, tmp)
            Traversal(cur.right, tmp)
            tmp.append(cur.val)

        res = []
        Traversal(root, res)
        return res

一、迭代遍历

(1)前序

class Solution:
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if not root: return []
        stack = [root]
        res = []
        #出栈顺序是中左右  所以先加入右孩子 再加入左孩子
        while stack:
            node = stack.pop()
            res.append(node.val)
            if node.right:
                stack.append(node.right)
            if node.left:
                stack.append(node.left)
        return res

(2)中序

class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        cur = root
        stack = []
        res = []
        #指针为空 且同时 栈也为空  终止循环
        while stack or cur:
            if cur:
                stack.append(cur)
                cur = cur.left
            else:
                cur = stack.pop()
                res.append(cur.val)
                cur = cur.right
        return res

(3)后序

class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if not root: return []
        stack = [root]
        res= []
        #前序遍历 入栈顺序是 中左右   中进去 弹出 再右左  "达到弹出是中左右的顺序"
        #如果反转 就变成  左右中    (中右左  逆转)
        while stack:
            node = stack.pop()
            res.append(node.val)
            if node.left:
                stack.append(node.left)
            if node.right:
                stack.append(node.right)
            
        return res[::-1]

你可能感兴趣的:(leetcode,算法,职场和发展)