A collection of nodeds and edges
Tree where each node has at most two children
코드 구현
class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
const a = new Node('a');
const b = new Node('b');
const c = new Node('c');
const d = new Node('d');
const e = new Node('e');
const f = new Node('f');
a.left = b;
a.right = c;
b.left = d;
b.right = e;
c.right = f;
Starting at the root and Exploring all nodes in the same level
Breadth-First Algorithm Startegy
코드 구현
class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
const a = new Node('a');
const b = new Node('b');
const c = new Node('c');
const d = new Node('d');
const e = new Node('e');
const f = new Node('f');
a.left = b;
a.right = c;
b.left = d;
b.right = e;
c.right = f;
const breadthFirstPrint = (root) => {
const queue = [ root ];
while (queue.length > 0) {
const curr = queue.shift();
console.log(curr.val);
if(curr.left !== null) {
queue.push(curr.left);
}
if(curr.right !== null) {
queue.push(curr.right);
}
}
};
const bfs = (root, target) => {
const queue = [ root ];
while (queue.length > 0) {
const curr = queue.shift();
if(curr.val === target) {
return true;
}
if(curr.left !== null) {
queue.push(curr.left);
}
if(curr.right !== null) {
queue.push(curr.right);
}
}
return false;
};
const sumTree = (root) => {
const queue = [ root ];
let sum = 0;
while (queue.length > 0) {
const curr = queue.shift();
sum += curr.val;
if(curr.left !== null) {
queue.push(curr.left);
}
if(curr.right !== null) {
queue.push(curr.right);
}
}
return sum;
};
console.log(breadthFirstPrint(a)); // abcdef
console.log(bfs(a, "e")); // true
console.log(bfs(a, "z")); // false
참고: codebyte - Intro to Binary Trees and Breadth First Traversal