Friday, June 3, 2022

700. Search in a Binary Search Tree


一刷 05/2022

Version #1 Iteration


Runtime: 0 ms, faster than 100.00% of Java online submissions for Search in a Binary Search Tree.
Memory Usage: 42.7 MB, less than 72.52% of Java online submissions for Search in a Binary Search Tree.

 /**

 * Definition for a binary tree node.

 * public class TreeNode {

 *     int val;

 *     TreeNode left;

 *     TreeNode right;

 *     TreeNode() {}

 *     TreeNode(int val) { this.val = val; }

 *     TreeNode(int val, TreeNode left, TreeNode right) {

 *         this.val = val;

 *         this.left = left;

 *         this.right = right;

 *     }

 * }

 */

class Solution {

    public TreeNode searchBST(TreeNode root, int val) {

        TreeNode curr = root;

        while (curr != null) {

            if (curr.val == val) {

                return curr;

            }

            if (curr.val > val) {

                curr = curr.left;

            } else {

                curr = curr.right;

            }

        }

        return null;

    }

}

No comments:

Post a Comment