230. Kth Smallest Element in a BST

来源:互联网 发布:数控pmc编程 编辑:程序博客网 时间:2024/05/21 14:47

1. 原题

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note:
You may assume k is always valid, 1 ≤ k ≤ BST’s total element.

2. 分析

  • 题目要求找出宽度优先树中的第K小的树。
  • 在没有这棵树的数据的情况下不知道哪些数是存在的, 所以要确定第K个树, 必须要遍历一遍树。得到所有数之后排序就可以得到第K小的数了
  • 宽度优先和深度优先的遍历都有规律可循, 分别判断根, 坐子树和右子树, 基本普通的遍历都是这个模式, 需要考虑的是退出情况还有传参的方式, 这里使用引用传参比较方便
 if (root != NULL){            nums.push_back(root->val);        }        if (root->left != NULL) getNums(root->left, nums);        if (root->right != NULL) getNums(root->right, nums);}

3.代码

/** * 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:    void getNums(TreeNode* root, vector<int>& nums){        if (root != NULL){            nums.push_back(root->val);        }        if (root->left != NULL) getNums(root->left, nums);        if (root->right != NULL) getNums(root->right, nums);    }    int kthSmallest(TreeNode* root, int k) {        vector<int> nums;        int len = nums.size();        getNums(root, nums);        sort(nums.begin(), nums.end());        return nums[k-1];    }};
原创粉丝点击