[LC] 700 title Search in a Binary Search Tree (search binary search tree) (binary search tree)

① Chinese title

Given a binary search tree (BST) and the root of a value. You need to find a node is equal to the value of a given node in the BST. Back to the subtree rooted at the node. If the node does not exist, NULL is returned.

E.g,

Given binary search tree:

 

 In the above example, if the values are looking for  5, but because there is no node value  5, we should return  NULL.

② ideas

    This is a nice thought,

    1, it is determined whether the current node is empty, if yes, then return null.

    2, look at the current value are equal with the node val, if such return root.

    3, if the value of the current node if <val, if it is less than, it means that the output current root val left, put the left of the current root sent recursively.

   4, if the value of the current node whether> val, if it is larger than it is described in the right of the current output val root, leave the current root right sent recursively.

③ Code

 1 class Solution {
 2     public TreeNode searchBST(TreeNode root, int val) {
 3         if(root==null)
 4             return null;
 5         if(root.val==val)
 6             return root; 
 7         else if(root.val>val)
 8             return searchBST(root.left,val);
 9         else
10             return searchBST(root.right,val);  
11     }
12 }

 

④ learned

    1, go left or go right, there is no bigger than with val.

    2, learn recursion.

Guess you like

Origin www.cnblogs.com/zf007/p/11610590.html