首页 > 技术文章 > 二叉树遍历:考虑空节点

r1-12king 2020-05-31 11:21 原文

思路:

  通常我们进行二叉树的遍历(前序遍历、中序遍历和后序遍历)时,不考虑空节点。但有时需要我们将空节点也放入遍历序列中。

  由于考虑了空节点,不能再用是否为空作为递归结束的条件。容易想到,只要一个节点非空,并且它的左右叶节点不同时为空,则其左右叶节点均要被遍历。这样我们就得到了考虑空节点的遍历。

  以中序遍历为例:
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def traval(self, root):
        if not root:
            return None
        global res
        res = []

        def mid_order(root):
            if root and (root.left or root.right):
                mid_order(root.left)
                res.append(root)
                mid_order(root.right)
            else:
                res.append(root)

        mid_order(root)

        return res

 

 

推荐阅读