二叉树前中后序遍历

  • 先序:考察到一个节点后,即刻输出该节点的值,并继续遍历其左右子树。(根左右)
  • 中序:考察到一个节点后,将其暂存,遍历完左子树后,再输出该节点的值,然后遍历右子树。(左根右)
  • 后序:考察到一个节点后,将其暂存,遍历完左右子树后,再输出该节点的值。(左右根)

前序遍历

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

方法一

class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        if root is None:
            return []
        left = self.preorderTraversal(root.left)
        right = self.preorderTraversal(root.right)
        return [root.val] + left + right

方法二

class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        temp = []
        ans = []
        if root is None:
            return []
        temp.append(root)
        while temp:
            root = temp.pop()
            ans.append(root.val)
            if root.right:
                temp.append(root.right)
            if root.left:
                temp.append(root.left)
        return ans

中序遍历

方法一

class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        if root is None:
            return []
        left = self.inorderTraversal(root.left)
        right = self.inorderTraversal(root.right)
        return left + [root.val] + right

方法二

class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        temp = []
        ans = []
        while root or temp:
            if root:
                temp.append(root)
                root = root.left
            else:
                root = temp.pop()
                ans.append(root.val)
                root = root.right
        return ans

后序遍历

方法一

class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        if not root:
            return []
        left = self.postorderTraversal(root.left)
        right = self.postorderTraversal(root.right)
        return left + right + [root.val]

方法二

class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        temp = []
        temp.append(root)
        ans = []
        pre = None
        if root is None:
            return []
        while temp:
            tmp = temp[-1]
            if (tmp.left is None and tmp.right is None) or (pre and (pre == tmp.left or pre == tmp.right)):
                ans.append(tmp.val)
                pre = tmp
                temp.pop()
            else:
                if tmp.right:
                    temp.append(tmp.right)
                if tmp.left:
                    temp.append(tmp.left)
        return ans
posted @ 2020-10-26 23:19  0-1-world  阅读(628)  评论(0编辑  收藏  举报