js遍历树算出树的深度

 
 
个人理解是层次遍历,最后一个循环遍历的时候是最后一层,这一层也是要计入深度的,故在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>

猜你喜欢

转载自blog.csdn.net/lh376152/article/details/73847815