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.
对于 tail recursion 的, 都是可以换成iterative, 把栈空间换成堆空间
//recursive: time: o(h) space: o(h) public TreeNode search(TreeNode root, int key) { // Write your solution here. if (root == null ) { return root ; } if (root.key == key) { return root ; } else if (root.key < key) { return search(root.right, key); } else { return search(root.left, key); } } /*iterative way of doing: time: o(h) space: o(1) this is tail recursion: recursion happens at the last statement */ public TreeNode search_iter(TreeNode root, int key){ if (root == null) { return root ; } TreeNode curr = root ; //very like linked list. while(curr != null){ if (curr.key == key) { break ; } else if (curr.key < key ) { curr = curr.right ; } else { curr = curr.left ; } } return curr ; }