求二叉树的最大深度的递归版与非递归版

185 阅读1分钟

1、递归版本

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;
    }
}

2、非递归版本

import java.util.LinkedList;
import java.util.Queue;

class Solution {
    Queue<TreeNode> queue = new LinkedList<>();

    public int maxDepth(TreeNode root) {
        if (root == null)
            return 0;
        queue.offer(root);
        int depth = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left != null)
                    queue.offer(node.left);
                if (node.right != null)
                    queue.offer(node.right);
            }
            depth++;
        }
        return depth;
    }
}