Depth First Search in Binary Tree
Sat Mar 30 2024
inOrderDFS:
A function meticulously crafted to navigate through a binary tree in search of a specified target value. Beginning at the root, it delves into the tree, prioritizing leftward exploration to its deepest leaf before examining the current node and proceeding rightward. This method adheres to the DFS principle, prioritizing depth over breadth in its search pattern. Upon encountering the target, the function promptly returns a positive confirmation, signaling the target's presence within the tree. This targeted search showcases the efficiency of DFS in locating specific values, illustrating the method's effectiveness in tree-based data structure manipulation.
1class Node {
2  constructor(val) {
3    this.val = val;
4    this.left = null;
5    this.right = null;
6  }
7}
8
9const one = new Node(1);
10const two = new Node(2);
11const three = new Node(3);
12const four = new Node(4);
13const five = new Node(5);
14const six = new Node(6);
15one.left = two;
16one.right = three;
17two.left = four;
18two.right = five;
19three.right = six;
20
21const inOrderDFS = (root, target) => {
22  if (!root) return null;
23  if (root.val === target) return true;
24  const leftSearch = inOrderDFS(root.left, target);
25  if (leftSearch) return leftSearch;
26  return inOrderDFS(root.right, target);
27};
28console.log(inOrderDFS(one, 4));
29console.log(inOrderDFS(one, 3));
30console.log(inOrderDFS(one, 7));
31console.log(inOrderDFS(one, 6));
32