104. 二叉树的最大深度

解法一:从上到下计算(后序遍历)

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

解法二:从上到下计算(层序遍历)

class Solution {
    public int maxDepth(TreeNode root) {
            if (root == null) {
            return 0;
        }
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int result = 0;
        while (!queue.isEmpty()) {
            result++;
            int length= queue.size(); //坑点,将queue.size() 直接放入for循环
            for (int i = 0; i < length; i++) {
                TreeNode poll = queue.poll();
                if (poll.left != null) {
                    queue.offer(poll.left);
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
                }
            }
        }
        return result;
    }
}
posted @ 2021-09-14 19:47  微笑带你去  阅读(32)  评论(0)    收藏  举报