目录
- 题目
- 思路1:递归遍历得到result数组(单调递增),然后对数组进行前后差分,取最小值
- 思路2:不用数组,进行优化
- 思路3、回顾迭代法求解
题目
给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。
思路1:递归遍历得到result数组(单调递增),然后对数组进行前后差分,取最小值
/*** 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:void traversal(TreeNode* cur , vector<int>& vec){if(cur == NULL) return;traversal(cur->left,vec);vec.push_back(cur->val);traversal(cur->right,vec);}int getMinimumDifference(TreeNode* root) {vector<int> result;traversal(root,result);//递增序列,所以绝对值的最小值就在差分数组中int Minimum =INT_MAX;for(int i =1;i<result.size();i++){Minimum = min(result[i]-result[i-1],Minimum);}return Minimum;}
};
不过这样的效率感觉比较低。
思路2:不用数组,进行优化
/*** 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 Minimum =INT_MAX; TreeNode* pre =NULL; //用来记录前一个结点void traversal(TreeNode* cur){if(cur == NULL) return;traversal(cur->left);if(pre != NULL ) Minimum = min(cur->val-pre->val,Minimum);pre = cur; //更新结点traversal(cur->right);}int getMinimumDifference(TreeNode* root) {traversal(root);return Minimum;}
};
思路3、回顾迭代法求解
/*** 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 getMinimumDifference(TreeNode* root) {stack<TreeNode*> st;int Minimum =INT_MAX; TreeNode* cur = root;TreeNode* pre = NULL; while(!st.empty() || cur!=NULL){if(cur!=NULL){st.push(cur);cur = cur->left;}else{cur = st.top();st.pop();if(pre != NULL ) Minimum = min(cur->val-pre->val,Minimum);pre = cur; //更新结点cur = cur->right;}} return Minimum;}
};