zoukankan      html  css  js  c++  java
  • 700. 二叉搜索树中的搜索

    给定二叉搜索树(BST)的根节点和一个值。 你需要在BST中找到节点值等于给定值的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 NULL。

    例如,

    给定二叉搜索树:
    
            4
           / 
          2   7
         / 
        1   3
    
    和值: 2
    

    你应该返回如下子树:

          2     
         /    
        1   3
    

    在上述示例中,如果要找的值是 5,但因为没有节点值为 5,我们应该返回 NULL

    /**
    //递归
    * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode searchBST(TreeNode root, int val) { if(root == null) return null; if (root.val == val) { return root; } else if (val < root.val) { return searchBST(root.left,val); } else { return searchBST(root.right,val); } } }

     迭代:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public TreeNode searchBST(TreeNode root, int val) {
            while(root != null) {
                if(val == root.val) return root;
                else if(val > root.val) root = root.right;
                else root = root.left;
            }
            return null;
        }
    }
  • 相关阅读:
    搭建JMeter+Jenkins+Ant持续化
    pytest+allure +requests接口自动化
    pytest + allure自动化测试
    测试流程
    unittest单元测试
    面向对象(三)----私有属性,方法
    文件的相关操作
    vue获取元素宽、高、距离左边距离,右,上距离等还有XY坐标轴
    富文本插件
    cursor
  • 原文地址:https://www.cnblogs.com/Roni-i/p/10458357.html
Copyright © 2011-2022 走看看