方法一
这个解法是从牛客上找的,有点儿没太看懂,先记录下来,回头再看
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function TreeDepth(pRoot)
{
// write code here
if(!pRoot) return 0;
let queue = [];
queue.push(pRoot);
let level = 0;
while(queue.length){
let sd = queue.length;
while(sd--){
let node = queue[0];
//开始的位置,截取的个数,替换的值
//queue中数被取出后,剩下的
queue.splice(0,1);
if(node.left) queue.push(node.left)
if(node.right) queue.push(node.right)
}
level++
}
return level
}
module.exports = {
TreeDepth : TreeDepth
};
方法二递归
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function TreeDepth(pRoot)
{
// write code here
if(!pRoot) return 0;
//有就去循环,没有就返回0
let l = pRoot.left ? TreeDepth(pRoot.left):0;
let r = pRoot.right ? TreeDepth(pRoot.right):0;
return Math.max(l,r)+1;
}
module.exports = {
TreeDepth : TreeDepth
};