38-二叉树的深度

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

//递归
/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function TreeDepth(pRoot)
{
    // write code here
    if(!pRoot) return 0;
    var left =  TreeDepth(pRoot.left);
    var right = TreeDepth(pRoot.right);
    return Math.max(left, right) + 1;
}
//非递归
/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function TreeDepth(pRoot)
{
    // write code here
    if(!pRoot) return 0;
    if(!pRoot.left && !pRoot.right) return 1;
    var cur = pRoot;
    var queue = [pRoot, null]; //加个标志位表示一层
    var depth = 1;
    while((cur = queue.shift()) !== undefined){
        if(cur == null) {
            if(queue.length == 0 ) return depth; //防止死循环
            depth++;
            queue.push(null);
            continue;
        }
        if(cur.left) queue.push(cur.left);
        if(cur.right) queue.push(cur.right)
    }
    return depth;
}
发布了81 篇原创文章 · 获赞 0 · 访问量 1983

猜你喜欢

转载自blog.csdn.net/weixin_43655631/article/details/104054943