上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int kthLargest(TreeNode* root, int k) {
}
};
golang 解法, 执行用时: 8 ms, 内存消耗: 6.3 MB, 提交时间: 2021-03-19 23:32:50
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func kthLargest(root *TreeNode, k int) int {
count := make([]int, 1)
visit(root, &count)
return count[len(count)-k]
}
func visit(node *TreeNode, count *[]int) {
if node.Left != nil {
visit(node.Left, count)
}
if node != nil {
*count = append(*count, node.Val)
}
if node.Right != nil {
visit(node.Right, count)
}
}
python3 解法, 执行用时: 80 ms, 内存消耗: 18.5 MB, 提交时间: 2021-03-17 22:37:18
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def kthLargest(self, root: TreeNode, k: int) -> int:
# 二叉搜索树的中序遍历就是有序的
rs = self.visit(root, [])
return rs[-k]
def visit(self, node: TreeNode, rs: list):
if node is None:
return rs
if node.left:
self.visit(node.left, rs)
rs.append(node.val)
if node.right:
self.visit(node.right, rs)
return rs
python3 解法, 执行用时: 72 ms, 内存消耗: 18.5 MB, 提交时间: 2021-03-17 22:30:58
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def kthLargest(self, root: TreeNode, k: int) -> int:
stack = [root]
rs = []
while len(stack) != 0:
t = stack.pop()
if t:
rs.append(t.val)
if t.left:
stack.append(t.left)
if t.right:
stack.append(t.right)
rs.sort()
return rs[-k]