二叉树遍历(DFS和BFS)- python

二叉树的遍历算法 深度优先搜索、广度优先搜索和深度优先搜索返回路径
class TreeNode:

    def __init__(self, value):
        self._value       = value
        self._parent_node = None
        self._left_node   = None
        self._right_node  = None

    def get_right_branch(self):
        return self._right_node

    def get_left_branch(self):
        return self._left_node

    def get_parent_branch(self):
        return self._parent_node

    def set_right_branch(self, node):
        self._right_node = node

    def set_left_branch(self, node):
        self._left_node = node

    def set_parent_branch(self, node):
        self._parent_node = node

    def get_value(self):
        return self._value

    def set_value(self, value):
        self._value = value

    def __str__(self):
        return "Node Value: {}".format(self._value)

def create_binary_tree():
    #
    #           n5
    #          /  \
    #         n2   n8
    #        / \   /
    #       n1 n4 n6
    #               \
    #               n7
    #
    n5 = TreeNode(5)
    n2 = TreeNode(2)
    n1 = TreeNode(1)
    n4 = TreeNode(4)
    n8 = TreeNode(8)
    n6 = TreeNode(6)
    n7 = TreeNode(7)

    n5.set_left_branch(n2)
    n2.set_parent_branch(n5)
    n5.set_right_branch(n8)
    n8.set_parent_branch(n5)
    n2.set_left_branch(n1)
    n1.set_parent_branch(n2)
    n2.set_right_branch(n4)
    n4.set_parent_branch(n2)
    n8.set_left_branch(n6)
    n6.set_parent_branch(n8)
    n6.set_right_branch(n7)
    n7.set_parent_branch(n6)
    return n5


def DFS_binary(root, fcn):
    stack = [root]
    while len(stack) > 0:
        if fcn(stack[0]):
            return True
        else:
            temp = stack.pop(0)
            if temp.get_right_branch():
                stack.insert(0, temp.get_right_branch())
            if temp.get_left_branch():
                stack.insert(0, temp.get_left_branch())
    return False

def BFS_binary(root, fcn):
    queue = [root]
    while len(queue) > 0:
        if fcn(queue[0]):
            return True
        else:
            temp = queue.pop(0)
            if temp.get_left_branch():
                queue.append(temp.get_left_branch())
            if temp.get_right_branch():
                queue.append(temp.get_right_branch())
    return False

# trace path
def DFS_binary_path(root, fcn):
    stack = [root]
    while len(stack) > 0:
        if fcn(stack[0]):
            return trace_path(stack[0])
        else:
            temp = stack.pop(0)
            if temp.get_right_branch():
                stack.insert(0, temp.get_right_branch())
            if temp.get_left_branch():
                stack.insert(0, temp.get_left_branch())
    return False

def trace_path(node):
    if not node.get_parent_branch():
        return [node]
    else:
        return trace_path(node.get_parent_branch()) + [node]

def find6(node):
    print("at node : {}".format(node.get_value()))
    return node.get_value() == 6

def find10(node):
    print("at node : {}".format(node.get_value()))
    return node.get_value() == 10

if __name__ == "__main__":
    root = create_binary_tree()
    print("####### DFS #######")
    DFS_binary(root, find6)
    print("-----------------")
    DFS_binary(root, find10)
    print("####### BFS #######")
    BFS_binary(root, find6)
    print("-----------------")
    BFS_binary(root, find10)
    print("#### DFS - Path ####")
    pathto_6_list = DFS_binary_path(root, find6)
    print("root -> goal")
    for e in pathto_6_list:
        print(e.get_value(), end = " ")
Python中的二叉树遍历可以使用广度优先搜索(BFS)和深度优先搜索(DFS)两种方法。 BFS(广度优先搜索)是一种逐层遍历二叉树的方法。从根节点开始,按照层级顺序依次访问每个节点,先访问左子节点,再访问右子节点。具体实现可以使用队列来辅助实现。以下是BFS的实现方式: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def bfs(root): if not root: return [] queue = [root] result = [] while queue: node = queue.pop(0) result.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) return result ``` DFS(深度优先搜索)是一种先访问根节点,然后递归地访问左子树和右子树的方法。DFS有三种常见的遍历方式:前序遍历、中序遍历和后序遍历。以下是DFS的实现方式: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def dfs_preorder(root): if not root: return [] result = [] result.append(root.val) result += dfs_preorder(root.left) result += dfs_preorder(root.right) return result def dfs_inorder(root): if not root: return [] result = [] result += dfs_inorder(root.left) result.append(root.val) result += dfs_inorder(root.right) return result def dfs_postorder(root): if not root: return [] result = [] result += dfs_postorder(root.left) result += dfs_postorder(root.right) result.append(root.val) return result ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值