-
思路一:中序遍历 得到升序数组,遍历得到min
-
思路二:中序遍历 的过程中用pre记录前一个结点的值,不需要创建数组。
-
顺便复习一下前中后序遍历
#思路一
class Solution {
public:
int getMinimumDifference(TreeNode* root) {
if(root==NULL) return -1;
stack<TreeNode*> call;
if(root) call.push(root);
vector<int> inorder;
int res=INT_MAX;
while(!call.empty()){
TreeNode* cur=call.top();
if(cur!=NULL){
call.pop();
if(cur->right) call.push(cur->right);
call.push(cur);
call.push(NULL);
if(cur->left) call.push(cur->left);
}else{
call.pop();
cur=call.top();
call.pop();
inorder.push_back(cur->val);
}
}
int size=inorder.size();
for(int i=0;i<size-1;i++){
res=min(res,inorder[i+1]-inorder[i]);
}
return res;
}
};
#思路二
class Solution {
public:
int getMinimumDifference(TreeNode* root) {
int res;
int pre=-1;
dfs(root,pre,res);
return res;
}
void dfs(TreeNode* root,int& pre,int & res){
if(root==NULL) return;
dfs(root->left,pre,res);
if(pre==-1){
pre=root->val;
}else{
res=min(res,root->val-pre);
pre=root->val;
}
dfs(root->right, pre, res);
}
};