力扣-230.二叉搜索树中第K小的元素
题目链接
230.二叉搜索树中第K小的元素
class Solution {int count = 0;int res = 0;public void InOrder(TreeNode root, int k) {if (root == null)return;InOrder(root.left, k);count++;if (count == k) {res = root.val;return;}InOrder(root.right, k);}public int kthSmallest(TreeNode root, int k) {InOrder(root, k);return res;}
}
小结:树的题目一般代码比较少,但需要在递归是思路清晰,此题将中序遍历函数设为无返回值,在遍历的同时进行计数和比较。