[LeetCode] #104 二叉树的最大深度

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

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

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

示例

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

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

二叉树的简单题原理都差不多,可以很好的学习递归和迭代

[LeetCode] #94 二叉树的中序遍历

[LeetCode] #100 相同的树

[LeetCode] #101 对称二叉树

递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        int res = 0;
        if(root == null) return res;
        res = Math.max(maxDepth(root.left), maxDepth(root.right))+1;
        return res;
    }
}

简化

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

迭代/层次遍历

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        Queue<TreeNode> tmpQueue = new LinkedList<TreeNode>();
        tmpQueue.offer(root);
        int res = 0;
        while (!tmpQueue.isEmpty()) {
            res++;
            for(int size = tmpQueue.size();size > 0;size--){
                TreeNode node = tmpQueue.poll();
                if (node.left != null) tmpQueue.offer(node.left);
                if (node.right != null) tmpQueue.offer(node.right);
            }
        }
        return res;
    }
}        

知识点:

总结:

 

posted @ 2021-08-05 15:09  1243741754  阅读(32)  评论(0编辑  收藏  举报