-
Notifications
You must be signed in to change notification settings - Fork 72
/
city.js
114 lines (112 loc) · 2.04 KB
/
city.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
const cityData = [
{
id: '1',
name: '广东省',
children: [
{
id: '11',
name: '深圳市',
children: [
{
id: '111',
name: '南山区',
},
{
id: '112',
name: '福田区',
children: [
{
id: '1121',
name: 'A街道',
},
],
},
{
id: '113',
name: '福田区',
children: [
{
id: '1131',
name: 'A街道',
},
],
},
],
},
{
id: '12',
name: '东莞市',
children: [
{
id: '121',
name: 'A区',
},
{
id: '122',
name: 'B区',
},
],
},
],
},
{
id: '2',
name: '湖北省',
children: [
{
id: '21',
name: '武汉市',
children: [
{
id: '211',
name: '洪山区',
},
{
id: '212',
name: '江夏区',
children: [
{
id: '2121',
name: 'A街道',
},
],
},
],
},
{
id: '22',
name: '鄂州市',
children: [
{
id: '221',
name: 'A区',
},
{
id: '222',
name: 'B区',
},
],
},
],
},
];
function findFather(cities, id) {
const stack = [];
const findNode = (cities, id) => {
let targetNode;
for (let city of cities) {
const { id: cityId, children } = city;
stack.push(city);
if (id === cityId) {
return city;
} else if (children) {
targetNode = findNode(children, id);
}
stack.pop();
}
return targetNode;
};
findNode(cities, id);
console.log(stack);
}
findFather(cityData, '2');