二叉搜索树中的搜索

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39360985/article/details/82891898

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

例如:

给定二叉搜索树:

        4
       / \
      2   7
     / \
    1   3

和值: 2

你应该返回如下子树:

      2     
     / \   
    1   3

在上述示例中,如果要找的值是 5,但因为没有节点值为 5,我们应该返回 NULL

通过此题掌握二叉搜索树的知识和递归的使用

题目分析:

给定一棵二叉搜索树,二叉搜索树的知识;找到一棵给定了根节点的子树,没有则返回null;

利用递归的知识,如果根节点的值等于给定的值val,则返回此根节点;如果根节点的值大于给定的值val,则递归遍历其左子树;如果根节点的值小于给定的值val,则递归遍历其右子树。

代码实现:

public static class TreeNode
{
   int data;
   TreeNode left;
   TreeNode right;
   TreeNode(int val)
   {
       data = val;
   }
}

public TreeNode searchBST(TreeNode root, int val)
{
   if (root == null)
       return null;
   if (root.data == val)
       return root;
   else if (root.data > val)
       return searchBST(root.left, val);
   else
       return searchBST(root.right, val);
}

主函数:

//中序遍历验证输出
public static void midPrint(TreeNode root)
{
   if (root != null)
   {
       midPrint(root.left);
       System.out.print(root.data + " ");
       midPrint(root.right);
   }
}

public static void main(String[] args)
{
   TreeNode p = new TreeNode(4);
   p.left = new TreeNode(2);
   p.right = new TreeNode(7);
   p.left.left = new TreeNode(1);
   p.left.right = new TreeNode(3);
   p.left.right.left = new TreeNode(1);

   Tree8 t = new Tree8();
   TreeNode q = t.searchBST(p, 2);

   midPrint(q);

}

构造的二叉搜索树P:

          4
         / \   
        2   7    
       / \   
      1   3
         /
        1    

运行结果:

1 2 1 3

猜你喜欢

转载自blog.csdn.net/qq_39360985/article/details/82891898