AQY:查找二叉树中值为k的节点

class TreeNode():
    def __init__(self, x: int):
        self.val = x;
        self.left = None
        self.right = None


class Tree():
    def __init__(self, k: int):
        self.k = k
        self.searchedNode = None

    # DFS 深度遍历 - 先序遍历
    def searchValueKTreeNode(self, node: TreeNode):
        if node is None:
            return

        if node.val == self.k:
            self.searchedNode = node
            return

        self.searchValueKTreeNode(node.left)
        self.searchValueKTreeNode(node.right)

    # BFS 层序遍历
    def searchBFSValueKTreeNode(self, node: TreeNode):
        if node is None:
            return

        queue = [root]
        while queue:
            tmp = []
            for node in queue:
                if node.val == self.k:
                    self.searchedNode = node
                    return
                if node.left: tmp.append(node.left)
                if node.right: tmp.append(node.right)

            queue = tmp


root = TreeNode(9)
secondNode = TreeNode(8)
threeNode = TreeNode(7)
fourNode = TreeNode(10)

root.left = secondNode
secondNode.left = threeNode
root.right = fourNode

tree = Tree(8)
tree.searchValueKTreeNode(root)
# tree.searchBFSValueKTreeNode(root)
print(tree)

 

你可能感兴趣的:(数据结构与算法,Python)