美文网首页
104. 二叉树的最大深度

104. 二叉树的最大深度

作者: Andysys | 来源:发表于2019-12-29 00:22 被阅读0次
    // 递归
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        return Math.max(leftDepth, rightDepth) + 1;
    }

    // 迭代 -- 效率低一些
    public int maxDepth2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<Pair<TreeNode, Integer>> queue = new LinkedList<>();
        queue.add(new Pair(root, 1));
        int depth = 0;
        while (!queue.isEmpty()) {
            Pair<TreeNode, Integer> current = queue.poll();
            root = current.fst;
            int currentDepth = current.snd;
            if (root != null) {
                depth = Math.max(depth, currentDepth);
                queue.add(new Pair(root.left, currentDepth + 1));
                queue.add(new Pair(root.right, currentDepth + 1));
            }
        }
        return depth;
    }

相关文章

网友评论

      本文标题:104. 二叉树的最大深度

      本文链接:https://www.haomeiwen.com/subject/qbbeoctx.html