-
-
Notifications
You must be signed in to change notification settings - Fork 241
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
查找json中的children路径 #44
Comments
const json = {
id: 1,
children: [
{ id: 2, children: [{ id: 3, children: [] }] },
{
id: 4,
children: [
{ id: 5, children: [] },
{ id: 6, children: [] },
],
},
{ id: 7, children: [] },
],
};
console.log(findNode(json, 5)); // 1->4->5
/**
* 每个节点id唯一,输出路径
* @param {*} json
* @param {*} target
*/
function findNode(json, target) {
function dfs(node, target, arr) {
if(!node) return;
arr.push(node.id);
if(node.id === target && !bool) {
res.push(...arr);
bool = true;
return;
}
try {
node.children && node.children.forEach(child => {
if(bool) throw new Error("IS FOUND");
dfs(child, target, arr);
arr.pop();
})
} catch(e) {
return;
}
}
const res = [];
let bool = false;
dfs(json, target, []);
return res.join('->');
} |
function findNode(id, node = json) {
if (node.id === id) {
return node.id.toString();
}
if (node.children.length === 0) {
return null;
}
for (let i = 0; i < node.children.length; i++) {
const result = findNode(id, node.children[i]);
if (result !== null) {
return node.id.toString() + "->" + result;
}
}
return null;
} |
function findNode(tree, targetId) {
let path = [],
res = []
traversal(tree)
return res.join('->')
function traversal(node) { // The parameter 'node' is an object
if (!node) return
path.push(node.id)
if (node.id === targetId) {
res.push(...path)
path.pop()
return
}
node.children && node.children.forEach(item => {
traversal(item)
})
path.pop()
}
}
console.log(findNode(tree, 5)) // 1->4->5 |
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
现有如下json(简化为对象),已知每个节点id唯一,编写findNode(id),返回路径,如findNode(5 输出 1->4->5
The text was updated successfully, but these errors were encountered: