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面试总结之框架问题
    数据库设计三大范式
    js 一些技巧
    el 和 fmt 常用
    iframe自适应高度
    MySQL基础
    任意精度整数算法 (BigInteger) 和任意精度小数算法 (BigDecimal)
    hibernate
    Struts2
    Servlet、Cookie、Session
  • 原文地址:https://www.cnblogs.com/immiao0319/p/15000455.html
Copyright © 2011-2022 走看看