leetcode#783. Minimum Distance Between BST Nodes
Problem Description
Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree.
Solution
EZ. 只要把二叉树先序遍历然后求出相邻两节点的最小差就可以了。
Code
/**
* 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 minDiffInBST(TreeNode* root) {
int minDiff = 100;
firstOrder(root);
for (int i=0; i<seq.size()-1; i++) {
if (seq[i+1] - seq[i] < minDiff) minDiff = seq[i+1] -seq[i];
}
return minDiff;
}
private:
vector<int> seq;
void firstOrder(TreeNode* root) {
if (!root) {
return;
}
firstOrder(root->left);
seq.push_back(root->val);
firstOrder(root->right);
}
};