很简答的一道题目,就是二叉树遍历找到某个节点的val是给出值,如果要返回的是以该节点为根节点的树,那么就是按照层级遍历,这里使用递归实现。如果找不到返回为空,如果找到返回该节点即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class 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) |
原文:https://www.cnblogs.com/chenguopa/p/15239878.html