[ツリー] 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

第二に、問題解決

方法a:層の前順

コードは何も言うことはありません、あなたが通過することができ、*と最初に直接戻るノードに、新しいツリーを構築する考え。

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;        
}

複雑性分析

  • 時間計算: ザ・ n個 O(N)
  • 宇宙の複雑さ: ザ・ n個 O(N)

方法2:再帰

*私は、二分探索木の再帰の性質をうまく利用し、ここに効率が低下しませんでした。

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);
}

複雑性分析

  • 時間計算: ザ・ n個 O(N)
  • 宇宙の複雑さ: ザ・ リットル インクルード グラム n個 O(LOGN)
公開された495元の記事 ウォンの賞賛105 ・は 30000 +を見て

おすすめ

転載: blog.csdn.net/qq_43539599/article/details/104873776