Uno, Título Descripción
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
, La solución segundo problema
Método a: preorden capa
Código hay nada que decir, se puede recorrer, * e inicialmente pensado para construir un nuevo árbol, directamente de vuelta al nodo.
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;
}
Análisis de la complejidad
- Complejidad de tiempo: ,
- Espacio de la complejidad: ,
Segundo método: recursiva
* No hice un buen uso de la naturaleza del binaria recursiva árbol de búsqueda aquí resultado en una menor eficiencia.
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);
}
Análisis de la complejidad
- Complejidad de tiempo: ,
- Espacio de la complejidad: ,