1. 程式人生 > 實用技巧 >DFS普通遞迴實現

DFS普通遞迴實現

<html>

<head>
    <!-- <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> -->
    <style>
    </style>
</head>
<div id="onMouseover"></div>

<body>
    <script>
        const tree = [{
            name: 'root',
            children: [
                {
                    name: 
'c1', children: [ { name: 'c11', children: [] }, { name: 'c12', children: [] } ] }, { name:
'c2', children: [ { name: 'c21', children: [] }, { name: 'c22', children: [] } ] } ] }]
// 深度優先的方式遍歷 列印 name // ['root', 'c1','c11', 'c12', 'c2', 'c21', 'c22'] let arr = [] function DFS(item) { let getLength = item.length if (getLength < 1 && !item.name) { return arr } for (let i = 0; i < getLength; i++) { arr.push(item[i].name) if (item[i].children.length > 0) { DFS(item[i].children) } } return arr } console.log(DFS(tree)) </script> </body> </html>