700. 二叉搜索树中的搜索

image.png
image.png

迭代

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public TreeNode searchBST(TreeNode root, int val) {
  12. //迭代
  13. /**
  14. * 递归与迭代的区别
  15. * 递归:重复调用函数自身实现循环称为递归;
  16. * 迭代:利用变量的原值推出新值称为迭代,或者说迭代是函数内某段代码实现循环;
  17. */
  18. while (root != null) {
  19. if(root.val == val) return root;
  20. else if(root.val < val) root = root.right;
  21. else if(root.val > val) root = root.left;
  22. }
  23. return null;
  24. }
  25. }