力扣算法ing(35 / 100)

3.22 104.二叉树的最大深度

我的思路:

dfs,深度优先搜索
或者说能不能先根搜索,
根  层数
3    1
9    2
null
max = 2
20   2
15   3
null 
max = 3
7    3
null 
max = 3

我的代码:

if(head.next === null) max return 
function maxDepth(root: TreeNode | null): number {
    function findMax(root: TreeNode | null , depth : number): number{
        if(root === null){
            return;
        }
        depth++;
        // 遍历左根
        findMax(root.left , depth);
        // 遍历右根
        findMax(root.right , depth);
    }
    const depth = findMax(root , 1);
    return depth;
};
输出undefied
因为findMax没有返回值

修改代码:


function maxDepth(root: TreeNode | null): number {
    function findMax(root: TreeNode | null , depth : number): number{
        if(root === null){
            return depth;
        }
        depth++;
        // 遍历右根
        const rightDepth = findMax(root.right , depth);
        // 遍历左根
        const leftDepth = findMax(root.left , depth);
        return Math.max(rightDepth , leftDepth);

    }
    return findMax(root , 1);
};
答案错误,比期待的答案多一个

问题应该出错在depth++,我们在使用findMax的时候,root的深度已经默认为1了,

但是,我们在这里又加了一个1,这样就会导致多了一个

return findMax(root , 0);

总结:

哈哈哈哈,现在已经进入树了,在经过昨天的那道题之后,对于树的先、中、后的遍历有了很大程度的理解,期待下一道题目!!!

你可能感兴趣的:(小白学习算法,算法,leetcode,typescript,javascript)