Skip to content

Commit 165ae1f

Browse files
committed
chore: tree
1 parent a967336 commit 165ae1f

File tree

2 files changed

+48
-3
lines changed

2 files changed

+48
-3
lines changed

README.md

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -178,12 +178,24 @@ Depth First Search (DFS) uses a `stack` for storing the nodes that it is visitin
178178

179179
Breadth First Search (BFS) uses a `queue` for storing the nodes that it is visiting.
180180

181-
### Trees
181+
### Tree
182182

183183
A tree has hierarchical data and it has nodes.
184184

185-
**root**: top node of tree is called root and has no parent.
186-
**node**: every node has parent ( except root ) and 0 or more children's.
185+
![](https://i.imgur.com/wUiUy0B.png)
186+
187+
- **Root**: top node of tree is called root and has no parent and has no incoming edges.
188+
- **Node**: every node has parent ( except root ) and 0 or more children's.
189+
- **Edge**: used to connect two nodes.
190+
- **Path**: A path is an ordered list of nodes that are connected by edges.
191+
- **Leaf**: A leaf node is a node that has no children.
192+
- **Height of the tree**: The height of a tree is the number of edges on the longest path between the root and a leaf.
193+
- **The level of node**: The level of a node is the number of edges on the path from the root node to that node.
194+
- **Children**: Nodes that have incoming edges from the same node to be said to be the children of that node.
195+
- **Parent**: Node is a parent of all the child nodes that are linked by outgoing edges. - **Sibling**: Nodes in the tree that are children of the same parent are called siblings.
196+
- **Ancestor**:  A node reachable by repeated moving from child to parent.
197+
198+
![](https://imgur.com/L04E7lo.png)
187199

188200
![](https://i.imgur.com/Jzwpguk.png)
189201

src/5-trees/1-implement-binary-tree.mjs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,37 @@ class TreeNode {
1919
this.data = data;
2020
this.children = [];
2121
}
22+
23+
addchild(value) {
24+
const child = new TreeNode(value);
25+
this.children.push(child);
26+
27+
return child;
28+
}
2229
}
30+
31+
export function display(tree) {
32+
let s = tree.data;
33+
let temp = tree.children;
34+
35+
if (tree.children) {
36+
return s;
37+
}
38+
39+
for (var i = 0; i < tree.children.length; i++) {
40+
let node = tree.children[i];
41+
s += ',' + node.data;
42+
43+
return display(node.children);
44+
}
45+
46+
s = ', ' + temp.data;
47+
48+
return s;
49+
}
50+
// Test
51+
52+
const tree = new TreeNode(1);
53+
tree.addchild(2);
54+
tree.addchild(3);
55+
console.log(display(tree));

0 commit comments

Comments
 (0)