diff --git a/problems/0700.二叉搜索树中的搜索.md b/problems/0700.二叉搜索树中的搜索.md index 5c1cdfdf..401c85d5 100644 --- a/problems/0700.二叉搜索树中的搜索.md +++ b/problems/0700.二叉搜索树中的搜索.md @@ -142,7 +142,78 @@ public: Java: +```Java +class Solution { + // 递归 + public TreeNode searchBST(TreeNode root, int val) { + if (root == null || root.val == val) { + return root; + } + TreeNode left = searchBST(root.left, val); + if (left != null) { + return left; + } + return searchBST(root.right, val); + } +} +class Solution { + // 递归,利用二叉搜索树特点,优化 + public TreeNode searchBST(TreeNode root, int val) { + if (root == null || root.val == val) { + return root; + } + if (val < root.val) { + return searchBST(root.left, val); + } else { + return searchBST(root.right, val); + } + } +} + +class Solution { + // 迭代 + public TreeNode searchBST(TreeNode root, int val) { + if (root == null || root.val == val) { + return root; + } + Stack stack = new Stack<>(); + stack.push(root); + while (!stack.isEmpty()) { + TreeNode pop = stack.pop(); + if (pop.val == val) { + return pop; + } + if (pop.right != null) { + stack.push(pop.right); + } + if (pop.left != null) { + stack.push(pop.left); + } + } + return null; + } +} + +class Solution { + // 迭代,利用二叉搜索树特点,优化,可以不需要栈 + public TreeNode searchBST(TreeNode root, int val) { + if (root == null || root.val == val) { + return root; + } + while (root != null) { + if (root.val == val) { + return root; + } else if (val < root.val) { + root = root.left; + } else { + root = root.right; + } + } + return null; + } +} +``` Python: