二叉树深度

二叉树的深度

http://www.nowcoder.com/questionTerminal/435fb86331474282a3499955f0a41e8b

二叉树深度

递归法

解法一

function TreeDepth(pRoot)
{
    return TreeWalk(pRoot,0)
 }

function TreeWalk(root,deep){
    if(root){
        return  Math.max(TreeWalk(root.left,deep+1),TreeWalk(root.right,deep+1))
    }
    else return deep
}

解法二

function TreeDepth(pRoot)
{
    if(!pRoot)return 0
    return  Math.max(TreeDepth(pRoot.left)+1,TreeDepth(pRoot.right)+1)
}

非递归解法

function TreeDepth(root){
    if(root == null)return 0;
    let level = [root]
    let result = 0;
    while(level.length){
        result++
        let newLevel = []
        for(let i = 0; i < level.length;i++){
            if(level[i].left)newLevel.push(level[i].left);
            if(level[i].right)newLevel.push(level[i].right);
        }
        level = newLevel;
    }
    return result;
}
全部评论

相关推荐

07-03 16:13
嘉应学院 Python
xiaolihuam...:很明显骗子,如果是hr直接约你面试了,哪用得着内推,如果是员工的话,你得多优秀,一线员工直接加你微信,
点赞 评论 收藏
分享
05-27 14:57
西北大学 golang
强大的社畜在走神:27届真不用急,可以搞点项目、竞赛再沉淀沉淀,我大二的时候还在天天打游戏呢
投递华为等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务