题目

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() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. public TreeNode searchBST(TreeNode root, int val) {
  18. if(root == null) return null;
  19. if(root.val == val) return root;
  20. TreeNode left = searchBST(root.left,val);
  21. if(left != null ) return left;
  22. TreeNode right = searchBST(root.right,val);
  23. return right;
  24. }
  25. }
  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. }