标签:返回值 二叉搜索树 pytho val pen elf range ref html
总结的DFS、BFS模板参考:https://www.cnblogs.com/panweiwei/p/13065661.html
class Solution(object):
# BFS
def kthLargest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
if not root:
return
res = []
stack = [root]
while stack:
sizestack = len(stack)
for i in range(sizestack):
node = stack.pop(0)
res.append(node.val)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
# 要返回的是第k大,所以降序排;若是第k小,则升序排
res.sort(reverse=True)
return res[k - 1]
class Solution(object):
# DFS:二叉搜索树的中序遍历就是有序序列。
def kthLargest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
if not root:
return
res = self.mid_DFS(root)
return res[len(res) - k]
def mid_DFS(self, root):
# 特判:树根为空
if not root:
return []
# 返回值
res = []
res += self.mid_DFS(root.left)
res.append(root.val)
res += self.mid_DFS(root.right)
return res
标签:返回值 二叉搜索树 pytho val pen elf range ref html
原文地址:https://www.cnblogs.com/panweiwei/p/13661834.html