天天看点

本题要求给定二叉树的4种遍历。_104. 二叉树的最大深度

本题要求给定二叉树的4种遍历。_104. 二叉树的最大深度

104. 二叉树的最大深度

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

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

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

示例: 给定二叉树

[3,9,20,null,null,15,7]

3
   / 
  9  20
    /  
   15   7
           

返回它的最大深度

3

作者:力扣 (LeetCode) 链接:https://leetcode-cn.com/leetbook/read/data-structure-binary-tree/xefh1i/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

题解:

本题就是简单的

DFS

的应用,没有什么特殊的技巧,通过递归,循环遍历整棵树。

具体代码如下:

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

本题也可用

BFS

做,但是时间复杂度不如深度优先搜索遍历。

具体代码如下:

class Solution {
    public int maxDepth(TreeNode root) {
        int depth = 0;
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

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

继续阅读