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.
1classNode{
2constructor(val) {
3this.val = val;
4this.left = null;
5this.right = null;
6 }
7}
89const 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;
2021const inOrderDFS = (root, target) => {
22if (!root) returnnull;
23if (root.val === target) returntrue;
24const leftSearch = inOrderDFS(root.left, target);
25if (leftSearch) return leftSearch;
26return 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