二叉搜索数的最小绝对差-二叉树

需要用到中序遍历

中序遍历

94. 二叉树的中序遍历 - 力扣(LeetCode)

递归

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        inoder(root,res);
        return res;
    }


    void inoder(TreeNode* root , vector<int>& res)
    {
        if(!root)
            return;
        
        inoder(root->left, res);
        res.push_back(root->val);
        inoder(root->right, res);
    }
};

迭代

一般的迭代法都是要用到栈,队列等来存root的

用栈,先进后出,中序遍历

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> stk;
        
        while(root != nullptr || !stk.empty()){
            while(root)
            {
                stk.push(root);
                root = root->left;
            }

            root = stk.top();
            stk.pop();
            res.push_back(root->val);

            root = root->right;
        }

        return res;
    }
};

530. 二叉搜索树的最小绝对差 - 力扣(LeetCode)

二叉搜索数的性质:二叉搜索树中序遍历得到的值序列是递增有序的

递归到最left的节点,也就是中序遍历最左边,开始ans = min(ans, root->val  - pre);

用pre来记上一个值;

INT_MAX是库里面的,表示最大的值,为了防止有比他小的;

class Solution {
public:

    void dfs(TreeNode* root, int& pre, int& ans)
    {
        if(root == nullptr)
            return;
        
        dfs(root->left, pre, ans);
        if(pre == -1){
            pre = root->val;
        }
        else{
            ans = min(ans, root->val - pre);
            pre = root->val;
        }

        dfs(root->right, pre, ans);
    }



    int getMinimumDifference(TreeNode* root) {
        int ans = INT_MAX , pre = -1;//初始化pre = -1,ans是最大值

        dfs(root, pre, ans);
        return ans;     
    }
};

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值