【树】C018_二叉搜索树中的搜索(递归 | 层序遍历)

一、题目描述

Given the root node of a binary search tree (BST) and a value. 
You need to find the node in the BST that the node's value equals the given value. 
Return the subtree rooted with that node. If such node doesn't exist, you should return NULL.

Given the tree:
        4
       / \
      2   7
     / \
    1   3

And the value to search: 2
You should return this subtree:

      2     
     / \   
    1   3

二、题解

方法一:层序遍历

代码没啥好说的,遍历即可, * 一开始还以为要构造一棵新树,直接返回该结点即可。

public TreeNode searchBST(TreeNode root, int val) {
  Queue<TreeNode> q1 = new LinkedList<>();
  q1.add(root);
  while (!q1.isEmpty()) {
      TreeNode node = q1.poll();
      if (node == null)
          continue;
      if (node.val == val) {
         return node;                 
      }
      q1.add(node.left);
      q1.add(node.right);
  }
  return null;        
}

复杂度分析

  • 时间复杂度: O ( n ) O(n)
  • 空间复杂度: O ( n ) O(n)

方法二:递归

* 这里我没有利用好二叉搜索树的性质导致递归效率较低。

TreeNode res = null;
public TreeNode searchBST(TreeNode root, int val) {
  dfs(root, val);
  return res;
}
private void dfs(TreeNode root, int val) {
  if (root == null)
      return;
  if (root.val == val)  {
      res = root;
      return;
  }
  dfs(root.left, val);
  dfs(root.right, val);
}
TreeNode res = null;
public TreeNode searchBST(TreeNode root, int val) {
  dfs(root, val);
  return res;
}
private void dfs(TreeNode root, int val) {
  if (root == null) return;
  if (root.val == val)  {
      res = root;
      return;
  }
  if (root.val < val) dfs(root.right, val);
  if (root.val > val) dfs(root.left, val);
}

复杂度分析

  • 时间复杂度: O ( n ) O(n)
  • 空间复杂度: O ( l o g n ) O(logn)
发布了495 篇原创文章 · 获赞 105 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/104873776
今日推荐