Given the root node of a binary search treerootReturns the minimum deviation of any two vertices in the tree.
Example:
Input:Root = [4, 2, 6, 1, 3, null, null]Output:1Explanation:Note that root is a tree Node object instead of an array. The given tree [4/2, 3, null, null] can be expressed as: 6/\ 1 3. The smallest difference is 1, which is the difference between node 1 and node 2, it is also the difference between node 3 and node 2.
Note:
- The size range of the binary tree is
2To100.
- Binary Trees are always valid. The values of each node are integers and are not repeated.
int minDiffInBST(TreeNode* root) { vector<int > res; inorder(root, res); int Min = 65535; for (int i = 0; i<res.size() - 1; i++){ Min = min(Min, res[i + 1] - res[i]); } return Min;}TreeNode * inorder(TreeNode* root, vector<int >&res){ if (root==NULL) return NULL; inorder(root->left, res); res.push_back(root->val); inorder(root->right, res); return root;}
783. Minimum Distance of the Binary Search Tree node