LeetCode700. 二叉搜索树中的搜索(Java)

题目:

给定二叉搜索树(BST)的根节点和一个值。 你需要在BST中找到节点值等于给定值的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 NULL。

示例:
LeetCode700. 二叉搜索树中的搜索(Java)
代码:

  • 解法一
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 //递归的思想
class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        if(root==null){	//如果根节点为空
           return null;
        }
        if(root.val>val){   //要找的值大于当前元素 向其左子树寻找
           return searchBST(root.left,val);
        }
        if(root.val<val){   //要找的值大于当前元素 向其右子树寻找
           return searchBST(root.right,val);
        }
        return root;    //找到元素
    }
}
  • 别人的代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 //迭代的思想
class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        if(root == null) {
            return null;
        }
        while(root != null) {
            if(val < root.val) {//要找的值大于当前元素 向其左子树寻找
                root = root.left;
            }else if(val > root.val) {  //要找的值大于当前元素 向其右子树寻找
                root = root.right;
            }else {
                return root;
            }
        }
        return null;
    }
}