时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32M,其他语言64M
热度指数:283761
本题知识点: 树
题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
方法一(递归)
function TreeDepth(pRoot)
{
if(!pRoot) {return 0;}
return 1 + Math.max(TreeDepth(pRoot.left), TreeDepth(pRoot.right));
}
方法二
function TreeDepth(pRoot)
{
if(!pRoot) {return 0;}
let arr = [];
arr.push(pRoot);
let length = 0, count = 0,round = 1;
while(arr.length !== 0){
count++;
let parent = arr.shift();
if(parent.left !== null){
arr.push(parent.left);
}
if(parent.right !== null){
arr.push(parent.right);
}
if(count == round){
count = 0;
round = arr.length;
length++;
}
}
return length;
}
注:push() :向数组的末尾添加一个或多个元素,并返回新的数组的长度
shift() :把数组的第一个元素从其中删除,并返回第一个元素的值