剑指 Offer 54. 二叉搜索树的第k大节点

tech2025-06-05  11

java

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { ArrayList<Integer> res = new ArrayList<>(); public int kthLargest(TreeNode root, int k) { recurr(root,k); return res.get(k-1); } void recurr(TreeNode root,int k){ if(root.right!=null){ recurr(root.right,k); } res.add(root.val); if(root.left!=null){ recurr(root.left,k); } } } /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { int i = 0; int res; public int kthLargest(TreeNode root, int k) { recurr(root,k); // return res.get(k-1); return res; } void recurr(TreeNode root,int k){ if(root.right!=null){ recurr(root.right,k); } i++; if(i == k ) res = root.val; if(root.left!=null){ recurr(root.left,k); } } }

解题思路: 第一种方法耗内存大,因为创建了ArrayList集合,利用集合存储遍历的值,第二种在遍历的时候判断遍历到了第几个,如果遍历到了第k个,就把第k个的值赋给res,最后返回res。

最新回复(0)