Search in LeetCode-700-Binary Search Tree

Source: Internet
Author: User

Specify the root node and a value of the Binary Search Tree (BST. You need to find the node whose value is equal to the given value in BST. Returns the subtree with the node as the root. If the node does not exist, null is returned.

For example,

Given Binary Search Tree: 4/2 7/1 3 and value: 2

You should return the following subtree:

      2          / \       1   3

In the preceding example5But because no node value is5, We should returnNULL.

Analysis: the binary search tree has the property that the Left subtree value is smaller than the root node, and the right subtree value is greater than the root node, therefore, if the value to be searched is smaller than the root node, you can continue searching in the left subtree. If the value is greater than the root node, you can continue searching in the right subtree.

Code:

 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         if(root == NULL){14             return NULL;15         }16         else if(root->val == val){17             return root;18         }19         else if(val > root->val){20             return(searchBST(root->right, val));21         }22         else if(val < root->val){23             return(searchBST(root->left, val));24         }25         else{26             return NULL;27         }28     }29 };

 

F

Search in LeetCode-700-Binary Search Tree

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.