104. 二叉树的最大深度

2019-12-29  本文已影响0人  Andysys
    // 递归
    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;
    }
上一篇 下一篇

猜你喜欢

热点阅读