很简答的一道题目,就是二叉树遍历找到某个节点的val是给出值,如果要返回的是以该节点为根节点的树,那么就是按照层级遍历,这里使用递归实现。如果找不到返回为空,如果找到返回该节点即可。
# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution: def searchBSTNodeList(self,rootList,val): if rootList == []: return None nextRootList = [] for node in rootList: if node.val == val: return node else: if node.left != None: nextRootList.append(node.left) if node.right != None: nextRootList.append(node.right) return self.searchBSTNodeList(nextRootList,val) def searchBST(self, root: TreeNode, val: int) -> TreeNode: return self.searchBSTNodeList([root],val)