第六章 二叉树part06

2026.03.14 02.14 第十八天

530 二叉搜索树的最小绝对差

本题很简单。关键是了解二叉搜索树在中序遍历下其实就是一个从小到大的有序数组。

每次遍历保存前一个节点的地址,而后与当前节点比较从而更新相邻节点的最小差值,最后然后将前一个节点的地址更新为当前节点地址即可。

class Solution {
private:
    int res;
    TreeNode* pre = nullptr;
    void travelsal(TreeNode* cur) {
        if(cur->left) travelsal(cur->left);
        
        if(pre) res = min(res, cur->val - pre->val);
        pre = cur;

        if(cur->right) travelsal(cur->right);
    }

public:
    int getMinimumDifference(TreeNode* root) {
        res = INT_MAX;
        travelsal(root);
        return res;
    }
};

用栈可以实现迭代法。

501 二叉搜索树中的众数

这题也简单,在上一题基础上做些改动,加上处理逻辑即可。

递归法:

class Solution {
private:
    vector<int> vec;
    int maxNum;
    int curNum;
    TreeNode* pre;
    void travelsal(TreeNode* cur) {
        if (cur->left) travelsal(cur->left);

        if(!pre) {
            curNum = 1;
		}
        else {
            if (pre->val != cur->val) curNum = 1;
			else if (pre->val == cur->val) curNum++;
        }
        if (curNum == maxNum) vec.push_back(cur->val);
        else if (curNum > maxNum) {
            vec.clear();
            vec.push_back(cur->val);
			maxNum = curNum;
        }
		pre = cur;


        if (cur->right) travelsal(cur->right);
    }

public:
    vector<int> findMode(TreeNode* root) {
        vec.clear();
        maxNum = 0;
        curNum = 0;
        pre = nullptr;

        travelsal(root);
        return vec;
    }
};

迭代法使用栈模拟递归即可。

236 二叉树的最近公共祖先

有点难度

感觉越写越搞不明白逻辑处理和终止条件该放在哪里了~
以及怎样遍历整个二叉树,什么时候找到目标值就立即结束查找~

迭代法:

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root == p || root == q || root == nullptr) return root;

        TreeNode* left = lowestCommonAncestor(root->left, p, q);

        TreeNode* right = lowestCommonAncestor(root->right, p, q);

        if(left != nullptr && right != nullptr) return root;

        if(left != nullptr && right == nullptr) return left;
        else if(left == nullptr && right != nullptr) return right;
        else return nullptr;
    }
};
posted @ 2026-03-14 16:15  遠くの君  阅读(0)  评论(0)    收藏  举报