zoukankan      html  css  js  c++  java
  • 700. Search in a Binary Search Tree 在bst中返回目标所在的最小子树

    You are given the root of a binary search tree (BST) and an integer val.

    Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.

     

    Example 1:

    Input: root = [4,2,7,1,3], val = 2
    Output: [2,1,3]
    

    Example 2:

    Input: root = [4,2,7,1,3], val = 5
    Output: []

    不懂的地方:
    不懂怎么才能返回的是一棵树:自然而然形成一棵树。因为没有继续递归下去了,所以就还带着附属的左右节点。

    有时候low/high只要有一个target就行了,所以其实也是traverse模板的变形!
    class Solution {
        public TreeNode searchBST(TreeNode root, int val) {
            if (root == null)
                return root;
            if (root.val == val)
                return root;
            else if (root.val > val)
                return searchBST(root.left, val);
            else if (root.val < val)
                return searchBST(root.right, val);
            return null;
        }
    }
    
    
    


     
  • 相关阅读:
    Java运行时内存
    java --对象流与对象的序列化
    Java 文件操作
    爬虫
    eclipse项目放到github
    越来越玄的JAVA
    map和set的遍历
    集合总览
    unsafe类
    狡诈的java并发容器
  • 原文地址:https://www.cnblogs.com/immiao0319/p/15000455.html
Copyright © 2011-2022 走看看