<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
function createNode(name, children) {
var o = new Object();
o.name = name;
o.children = children;
return o;
}
var a11=createNode('a11',[]);
var a12=createNode('a12',[]);
var a1 = createNode('a1', [a11,a12]);
var a2 = createNode('a2', []);
var a = createNode('a', [a1, a2]);
var b11=createNode('b11',[]);
var b12= createNode('b12',[]);
var b1=createNode('b1',[b11,b12]);
var b2=createNode('b2',[]);
var b3= createNode('b3',[]);
var b = createNode('b', [b1,b2,b3]);
var tree = createNode('root', [a, b]);
console.log(tree);
var path = [];
var found = false;
function search(node, dest) {
path.push(node.name);
if (node.name == dest) {
found = true;
console.log('found');
console.log(path);
return;
} else {
//节点不对
//分为两种情况 这个节点还有孩子 则继续 没有孩子则返回
if (node.children.length == 0) {
} else {
// &&!found 如果在某个节点中找到了 就不再到下一个兄弟节点中去
for (var i = 0; i < node.children.length && !found; i++) {
search(node.children[i], dest);
path.pop();
}
}
}
}
search(tree,'b2');
</script>
</body>
</html>