530
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
Input: 1 \ 3 / 2 Output: 1 Explanation: The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
Note:There are at least two nodes in this BST.
一道easy题,其实考察的是中序遍历的思想,因为BST的特性是左边<中间<右边,因此中序遍历刚好就是从小到大遍历。
主要注意的是中序遍历的写法。
class Solution {
public:
int mini = INT_MAX;
TreeNode* pre;
int getMinimumDifference(TreeNode* root) {
inorder(root);
return mini;
}
void inorder(TreeNode* root){
if(root == NULL) return ;
inorder(root->left);
if(pre != NULL) mini = min(mini, root->val - pre->val);
pre = root;
inorder(root->right);
}
};
这道题一开始没有对pre赋值,比较疑惑。后来想了一下,一开始遍历最左边的叶子节点,本来就不需要对mini进行更新,之后将pre赋值为最左边的叶子节点,正好啊。
230.
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?
Hint:
- Try to utilize the property of a BST.
- What if you could modify the BST node's structure?
- The optimal runtime complexity is O(height of BST).
中序做法:
/**
* 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 number = 0;
int count = 0;
void inorder(TreeNode* root){
if(root == NULL) return ;
inorder(root->left);
count--;
if(count == 0){
number = root->val;
return;
}
inorder(root->right);
}
int kthSmallest(TreeNode* root, int k) {
count = k;
inorder(root);
return number;
}
};
经过这两道中序遍历的题,之前对中序遍历的认识是一般都写成void,但是由于这两道题都需要在遍历的时候对某个常量进行操作,觉得可不可以返回Int之类的,尝试过后觉得还是很不对,看大家的一般做法也都是定义全局变量来解决在遍历的过程中修改某个定量的问题。
或者返回int的写法是这样的;
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
if (root == NULL)
return INT_MAX;
stack<TreeNode*> s;
TreeNode *temp = root;
while (!s.empty() || temp != NULL)
{
while (temp != NULL)
{
s.push(temp);
temp = temp->left;
}
temp = s.top();
k--;
if (k == 0)
return temp->val;
s.pop();
temp = temp->right;
}
return INT_MIN;
}
};
递归做法:
class Solution {
public:
int countNode(TreeNode* root){
if(root == NULL) return 0;
return countNode(root->left) + countNode(root->right) + 1;
}
int kthSmallest(TreeNode* root, int k) {
int left = countNode(root->left);
if(left + 1 == k) return root->val;
else if(left + 1 < k) return kthSmallest(root->right, k - left - 1);
else return kthSmallest(root->left, k);
}
};