Leetcode 700. 二叉搜尋樹中的搜尋(DAY 2)

錯不在我發表於2020-12-20

原題題目

在這裡插入圖片描述




程式碼實現

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
#define MAX 5000

struct TreeNode* searchBST(struct TreeNode* root, int val)
{
    if(!root)
        return NULL;
    int top = -1,rear = -1;
    struct TreeNode* queue[MAX];
    struct TreeNode* position;
    queue[++rear] = root;
    while(rear != top)
    {
        position = queue[++top];
        if(position->val == val)
            return position;
        if(position->left)
            queue[++rear] = position->left;
        if(position->right)
            queue[++rear] = position->right;
    }
    return NULL;
}

相關文章