简单题(二叉搜索树中第k小的元素)

在这里插入图片描述
很简单的中序遍历,代码如下:

//中序遍历
class Solution {
public:
	int kthSmallest(TreeNode* root, int k) {
		DFS(root, k);
		return res;
	}
	void DFS(TreeNode* root, int k) {
		if (root == NULL)
			return;
		DFS(root->left, k);
		num++;
		if (k == num)
		{
			res = root->val;
			return;
		}
		DFS(root->right, k);
	}
private:
	int res = 0;
	int num = 0;
};
发布了212 篇原创文章 · 获赞 4 · 访问量 8817

猜你喜欢

转载自blog.csdn.net/ShenHang_/article/details/104384536