zoukankan      html  css  js  c++  java
  • 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.

    对于 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 ;
        }
  • 相关阅读:
    tomcat的安装以及环境配置
    MySQL日期/时间函数
    docker部署tomcat
    Lambda的高级查询
    Linq的使用
    多线程编程
    反射
    匿名类型
    委托和事件
    泛型特性
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8680721.html
Copyright © 2011-2022 走看看