zoukankan      html  css  js  c++  java
  • 递归实现遍历二叉树

     1 <!doctype html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>Document</title>
     6 </head>
     7 <body>
     8 <script>
     9         var treeNodes = [
    10             {
    11                 id: "1",
    12                 name: 'name1',
    13                 children: [
    14                     {
    15                         id: "1-1",
    16                         name: 'name1-1',
    17                         children: [
    18                             {
    19                                 id: "1-1-1",
    20                                 name: 'name1-1-1',
    21                                 children:[]
    22                             },
    23                             {
    24                                 id: "1-1-2",
    25                                 name: 'name1-1-2'
    26                             }
    27                         ]
    28                     },
    29                     {
    30                         id: "1-2",
    31                         name: 'name1-2',
    32                         children: []
    33                     }
    34                 ],
    35                 users: []
    36             },
    37             {
    38                 id: "2",
    39                 name: 'name2',
    40                 children: [
    41                     {
    42                         id: "2-2",
    43                         name: 'name2-1',
    44                         children: []
    45                     }
    46                 ]
    47             }
    48         ];
    49 
    50         //递归实现
    51         var parseTreeJson = function(treeNodes){
    52             if (!treeNodes || !treeNodes.length) return;
    53 
    54             for (var i = 0, len = treeNodes.length; i < len; i++) {
    55 
    56                 var childs = treeNodes[i].children;
    57 
    58                 console.log(treeNodes[i].id+'ID');
    59 
    60                 if(childs && childs.length > 0){
    61                     parseTreeJson(childs);
    62                 }
    63             }
    64         };
    65 
    66         console.log('------------- 递归实现 ------------------');
    67         parseTreeJson(treeNodes);
    68 
    69 </script>
    70 </body>
    71 </html>

     此方法对二叉树提供的数据有要求,第一层循环遍历时,treeNodes,而后每深入一层,用的都是childs,比方说第二层就是children.children,第三层也是如此,这就要求提供的数据必须按照一定的格式;

    坚持下去就能成功
  • 相关阅读:
    Mysql 源码安装
    mysql的主从复制
    Centos7通过glib方式安装mysql
    Host is not allowed to connect to this MySQL server解决方法
    MobaXterm记录日志
    Linux的录屏
    ShardingJdbc垂直分库及公共表
    应用系统间几种数据传输方式
    关于加班
    对函数式编程的简单理解
  • 原文地址:https://www.cnblogs.com/suoking/p/4949941.html
Copyright © 2011-2022 走看看