LeetCode 700——二叉搜尋樹中的搜尋
阿新 • • 發佈:2018-11-19
1. 題目
2. 解答
如果根節點為空,直接返回 NULL。如果根節點非空,從根節點開始迴圈查詢,直到節點為空。
- 如果待查詢的值大於當前節點值,節點指向右孩子;
- 如果待查詢的值小於當前節點值,節點指向左孩子;
- 如果待查詢的值等於當前節點值,返回當前節點。
若迴圈結束還沒有找到,返回 NULL。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* searchBST(TreeNode* root, int val) { if (root == NULL) return NULL; TreeNode* temp = root; while(temp) { if (val < temp->val) temp = temp->left; else if (val > temp->val) temp = temp->right; else return temp; } return NULL; } };
獲取更多精彩,請關注「seniusen」!