一、题目
二、代码
/**
* 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
{
TreeNode return_node = null;
public void search_tree(TreeNode pro, int val)
{
if(return_node!=null) return;
if(pro.left!=null) search_tree(pro.left,val);
if(pro.val == val) return_node = pro;
if(pro.right!=null) search_tree(pro.right,val);
}
public TreeNode searchBST(TreeNode root, int val)
{
search_tree(root,val);
return return_node;
}
}
三、运行结果
四、附录
二刷
/**
* 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
{
TreeNode record = new TreeNode(-1);
public TreeNode searchBST(TreeNode root, int val)
{
if(record.val!=-1) return null;
if( root.val== val) record=root;
if(root.val>val&&root.left!=null) searchBST(root.left,val);
if(root.val<val&&root.right!=null) searchBST(root.right,val);
if(record.val == -1) return null;
return record;
}
}