左孩子右兄弟表示法的任意有根树的遍历

算法导论 p.248 10.4-4

题目描述:对于一个含n个结点的任意有根树,写出一个O(n)时间的过程,输出其所有关键字,该树以左孩子右兄弟表示法存储。

与二叉树的遍历类似

  • 树结构的定义:
class Tree:
    def __init__(self, val):
        self.val = val
        self.left_child = None
        self.right_bro = None
  • 使用栈实现了树的遍历
class Solution:
    def getAllNodeFromTreeByStack(self, tree=Tree) -> List[int]:
        if not self:
            return []
        resList, stack = [], list()
        stack.append(self)
        while stack:
            node = stack.pop()
            resList.append(node.val)
            if node.right_bro:
                stack.append(node.right_bro)
            if node.left_child:
                stack.append(node.left_child)
        return resList
  • 使用队列实现了树的遍历
class Solution:
    def getAllNodeFromTreeByQueue(self, tree=Tree) -> List[int]:
        if not self:
            return []
        resList, queue = [], collections.deque()
        queue.append(self)
        while queue:
            node = queue.popleft()
            resList.append(node.val)
            if node.right_bro:
                queue.append(node.right_bro)
            if node.left_child:
                queue.append(node.left_child)
        return resList
  • 使用递归实现了树的遍历
class Solution:
    def getAllNodeFromTreeByRecursion(self, tree=Tree) -> List[int]:
        if not self:
            return []
        resList = []
        if tree:
            resList.append(tree.val)
            if tree.right_bro:
                resList.extend(Solution.getAllNodeFromTreeByRecursion(self=self, tree=tree.right_bro))
            if tree.left_child:
                resList.extend(Solution.getAllNodeFromTreeByRecursion(self=self, tree=tree.left_child))
        return resList
  • 验证
if __name__ == '__main__':
    tree = Tree(0)
    tree.left_child = Tree(10)
    tree.left_child.right_bro = Tree(12)
    tree.left_child.right_bro.right_bro = Tree(-1)
    tree.left_child.right_bro.right_bro.right_bro = Tree(93)
    tree.left_child.right_bro.right_bro.right_bro.left_child = Tree(100)
    print(Solution.getAllNodeFromTreeByStack(self=tree, tree=tree))  # [0, 10, 12, -1, 93, 100]
    print(Solution.getAllNodeFromTreeByQueue(self=tree, tree=tree))  # [0, 10, 12, -1, 93, 100]
    print(Solution.getAllNodeFromTreeByRecursion(self=tree, tree=tree))  # [0, 10, 12, -1, 93, 100]

你可能感兴趣的:(每日算法学习,数据结构,python)