[LeetCode] Kth Smallest Element in a BST
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 elements.
Follow up:
What if the BST is modified (insert/delete operations) often and you
need to find the kth smallest frequently? How would you optimize the
kthSmallest routine?
分析:二叉搜索树中序遍历递增有序。
相关题目:《剑指offer》63
递归版本:
/** * 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) { TreeNode* p = kthSmallest(root, &k); return p->val; } TreeNode* kthSmallest(TreeNode* root, int* k) { TreeNode* p = NULL; if (root->left != NULL) { p = kthSmallest(root->left, k); } if (p == NULL) { if (*k == 1) p = root; (*k)--; } if (p == NULL && root->right != NULL) p = kthSmallest(root->right, k); return p; } };
迭代版本:
/** * 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) { TreeNode* p = root; stack<TreeNode*> s; int i = 0; while (p != NULL || !s.empty()) { if (p != NULL) { s.push(p); p = p->left; } else { p = s.top(); s.pop(); i++; if (i == k) return p->val; p = p->right; } } } };