树的搜索——leetcode

74. 搜索二维矩阵 - 力扣(LeetCode)

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int n = matrix.size(), m = matrix[0].size();
        int x = 0, y = m - 1;
        while(true)
        {
            if(x >= n || y < 0) return false;
            if(matrix[x][y] == target) return true;
            if(matrix[x][y] < target)
            {
                x ++;
            }
            else y --;
        }
        return true;
    }
};

173. 二叉搜索树迭代器 - 力扣(LeetCode)

class BSTIterator {
private:
    TreeNode* cur;
    stack<TreeNode*> stk;
public:
    BSTIterator(TreeNode* root): cur(root) {}
    
    int next() {
        while(cur != nullptr)
        {
            stk.push(cur);
            cur = cur->left;
        }
        cur = stk.top();
        stk.pop();
        int ret = cur->val;
        cur = cur->right;
        return ret;
    }
    
    bool hasNext() {
        return cur || !stk.empty();
    }
};

上一篇:【Rust】元组-transpose


下一篇:Leetcode---二维数组问题