题目:
解答:
方法一:递归
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode* searchBST(TreeNode* root, int val) 13 { 14 if(!root || root->val == val) 15 { 16 return root; 17 } 18 19 return root->val > val ? searchBST(root->left, val) : searchBST(root->right, val); 20 } 21 };
方法二:迭代
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode* searchBST(TreeNode* root, int val) 13 { 14 while(true) 15 { 16 if(!root || root->val == val) 17 { 18 return root; 19 } 20 root = root->val > val ? root->left : root->right; 21 } 22 } 23 };
原文:https://www.cnblogs.com/ocpc/p/12822002.html