Kth Smallest Element in a BST
原题链接Kth Smallest Element in a BST
给顶一个二叉搜索树的根节点,找到这棵数第k小的值
两种方法
递归法的中序遍历迭代法的中序遍历
递归法,常规的中序遍历
代码如下
/*** 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 kthSmallest(TreeNode* root, int k) {int res = 0;inOrder(root, k, res);return res;}private:void inOrder(TreeNode* root, int& k, int& res){if(!root || !k) return;inOrder(root->left, k, res);//找到k个数即可if(--k == 0)res = root->val;inOrder(root->right, k, res);}};
迭代法,用栈实现
/*** 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 kthSmallest(TreeNode* root, int k) {stack<TreeNode*> s;pushAllLeft(root, s);TreeNode* top = nullptr;while(k--){top = s.top();s.pop();//每弹出一个节点就将该节点的右子树的左边一列入栈pushAllLeft(top->right, s);}return top->val;}private:void pushAllLeft(TreeNode*root, stack<TreeNode*>& s){while(root){s.push(root);root = root->left;}}};
本题主要考察中序遍历,除了递归法最好可以熟悉迭代法的求解