LF.52.Search In Binary Search Tree

Posted davidnyc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LF.52.Search In Binary Search Tree相关的知识,希望对你有一定的参考价值。

 

Find the target key K in the given binary search tree, return the node that contains the key if K is found, otherwise return null.

Assumptions

There are no duplicate keys in the binary search tree

 

 1 public class Solution {
 2   public TreeNode search(TreeNode root, int key) {
 3     // Write your solution here.
 4     //base case
 5     if (root == null) {
 6         return null ;
 7     }
 8     if (root.key == key) {
 9         return root ;
10     }
11     if (root.key < key ) {
12         return search(root.right, key);
13     }
14     if (root.key > key) {
15         return search(root.left, key) ;
16     }
17     return null;
18   }
19 }

 

以上是关于LF.52.Search In Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章