js遍历树算出树的深度

来源:互联网 发布:淘宝类目搜索排名 编辑:程序博客网 时间:2024/05/28 17:04
个人理解是层次遍历,最后一个循环遍历的时候是最后一层,这一层也是要计入深度的,故在arr.length >= 0的时候,depth也是要自增加1的
<script type="text/javascript">    $(function(){        var json = {            "text" : "表格列名称",            "children" : [{                "text" : "序号",                "children" : [{                    "text" : "序号一",                    "children" : []                },{                    "text" : "序号二",                    "children" : []                }]            },{                "text" : "名称",                "children" : []            },{                "text" : "项目",                "children" : [{                    "text" : "项目一",                    "children" : [{                        "text" : "项目二",                        "children" : []                    },{                        "text" : "项目三",                        "children" : []                    }]                },{                    "text" : "项目一",                    "children" : [{                        "text" : "项目二",                        "children" : []                    },{                        "text" : "项目三",                        "children" : []                    }]                }]            }]        };        function getDepth(json) {            var arr = [];            arr.push(json);            var depth = 0;            while (arr.length > 0) {                var temp = [];                for(var i = 0 ; i < arr.length ; i++){                    temp.push(arr[i]);                }                arr = [];                for(var i = 0 ; i < temp.length ; i++){                    for(var j = 0 ; j < temp[i].children.length ; j++){                        arr.push(temp[i].children[j]);                    }                }                if(arr.length >= 0){                    depth++;                }            }            return depth;        }        alert(getDepth(json));    });</script>
原创粉丝点击