-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreatelistfromtree.js
84 lines (59 loc) · 1.19 KB
/
createlistfromtree.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth */
"use strict";
var LinkedList = require("./linkedlist");
function createListFromTreeDFS(node, lists, height) {
var list;
if(!node) {
return null;
}
if(lists === undefined) {
lists = [];
}
if(height === undefined) {
height = 0;
}
list = lists[height];
if(!list) {
list = new LinkedList();
lists[height] = list;
}
list.add(node);
createListFromTreeDFS(node.left, lists, height + 1);
createListFromTreeDFS(node.right, lists, height + 1);
return lists;
}
function createListFromTreeBFS(node) {
var lists = [],
list,
current,
parents,
parent,
head;
if(!node) {
return null;
}
current = new LinkedList();
current.add(node);
while(current.size() > 0) {
lists.add(current);
parents = current;
current = new LinkedList();
parent = parents.firstNode();
while(parent) {
if(parent.left) {
current.add(parent.left);
}
if(parent.right) {
current.add(parent.right);
}
parent = parent.next;
}
return lists;
}
}
module.exports = {
bfs: createListFromTreeBFS,
dfs: function(root) {
return createListFromTreeDFS(root);
}
};