剑指 Offer 55

思路:

统计层数,一开始想能不能dfs做,但怎么想感觉都不好做(脑袋里还是遍历的想法),然后自然就想到层序遍历,然后每次经过一层加一就行

class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null)
        {return 0;}
        Queue<TreeNode> queue=new LinkedList<>();
        int result=0;
        queue.add(root);
        while(queue.size()!=0)
        {
            result++;
            int count=queue.size();
            for(int i=0;i<count;i++)
            {
                root=queue.poll();
                if(root.left!=null)
                {queue.add(root.left);}
                if(root.right!=null)
                {queue.add(root.right);}
            }
        }
        return result;

    }
}

接着看到了递归写法

其实用递归思考这道题目不需要想这是什么遍历(其实是后序),逻辑已经足够清晰了:

class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
    }
}

这两个的时间复杂度应该是一样的,不知道为什么迭代出来时间会长一些

原文地址:https://www.cnblogs.com/take-it-easy/p/14367913.html