领扣LintCode算法问题答案-1524. 在二叉搜索树中查找

    科技2022-07-13  119

    领扣LintCode算法问题答案-1524. 在二叉搜索树中查找

    目录

    1524. 在二叉搜索树中查找描述样例 1:样例 2: 题解鸣谢

    1524. 在二叉搜索树中查找

    描述

    给定一颗二叉搜索树和 value.

    返回这棵树中值等于 value 的节点. 如果不存在这样的节点, 返回 null.

    样例 1:

    输入: value = 2 4 / \ 2 7 / \ 1 3 输出: 节点 2

    样例 2:

    输入: value = 5 4 / \ 2 7 / \ 1 3 输出: null

    题解

    /** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: the tree * @param val: the val which should be find * @return: the node */ public TreeNode searchBST(TreeNode root, int val) { // Write your code here. if (root == null) { return null; } TreeNode n = root; while (n != null && n.val != val) { if (val < n.val) { n = n.left; } else if (val > n.val) { n = n.right; } } return n; } }

    原题链接点这里

    鸣谢

    非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。 欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。

    Processed: 0.010, SQL: 8