数据结构总结-树

二叉树

  • 深度优先遍历方式
  1. 先序遍历: r o o t → l e f t → r i g h t root \rightarrow left \rightarrow right rootleftright
  2. 中序遍历: l e f t → r o o t → r i g h t left \rightarrow root \rightarrow right leftrootright    二叉搜索树
  3. 后序遍历: l e f t → r i g h t → r o o t left \rightarrow right \rightarrow root leftrightroot    删除节点的顺序
    https://leetcode-cn.com/problems/binary-tree-preorder-traversal/solution/er-cha-shu-de-qian-xu-bian-li-by-leetcode/
  • 代码(以中序遍历为例)
  1. 递归
class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        res = []
        def helper(root):
            if root is None:
                return
            helper(root.left)
            res.append(root.val)
            helper(root.right)   
        helper(root)
        return res
  1. 迭代: 颜色标记法,white,gray分别代表访问一次的结点和再次访问的结点
class Solution:
   def inorderTraversal(self, root: TreeNode) -> List[int]:
       white, gray = 0, 1
       res = []
       stack = [(white, root),]
       while stack:
           color, node = stack.pop()
           if node is None:
               continue
           if color == white:
               stack.extend([(white, node.right), (gray, node), (white, node.left)])
           else:
               res.append(node.val)
       return res

详见

  1. 颜色标记法-一种通用且简明的树遍历方法
  2. 递归和迭代遍历二叉树
  • BFS层次遍历方式
class Solution:
  def levelOrder(self, root):
      """
      :type root: TreeNode
      :rtype: List[List[int]]
      """
      if not root:
          return []
      res,cur_level = [],[root]
      while cur_level:
          temp = []
          next_level = []
          for i in cur_level:
              temp.append(i.val)
              if i.left:
                  next_level.append(i.left)
              if i.right:
                  next_level.append(i.right)
          res.append(temp)
          cur_level = next_level
      return res

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值