104 二叉树的最大深度

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7]

graph TD 11((3)) --- 21((9)) 11((3)) --- 22((20)) 21((9)) --- 31((null)) 21((9)) --- 32((null)) 22((20)) --- 33((15)) 22((20)) --- 34((7))

返回它的最大深度 3 。

递归解法

深度优先,在每个节点的深度为其左子树或右子树的深度加1。每个节点都会遍历到,因此时间复杂度为 \(O(n)\),空间复杂度为 \(O(n)\)

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null){
            return 0;
        }
        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        return left>right?left+1:right+1;
    }
}

迭代做法

广度优先,依次将每层的节点放入队列中,当一层中没有节点时,即树最深一层。时间复杂度为 \(O(n)\),空间复杂度为 \(O(n)\)

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        int ans = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
            ans++;
        }
        return ans;
    }
}
posted @ 2020-11-20 11:08  PotatoTed  阅读(82)  评论(0)    收藏  举报