Leetcode:104. 二叉树的最大深度

1.递归

要点:利用递归,只看一个头节点需要做哪些事。本题中,头节点只需看它的左子树和右子树哪个的深度最大,取其中最大的深度,再在最大深度基础上+1就是本节点的最大深度,因为必须先知道左子树右子树的高度,根节点再选取两者最大值加1,因此选用后序遍历。

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

2.层序遍历

层序遍历会遍历每一层,设置一个变量dept=0;每遍历一层加一,最终遍历完成后dept就是最大深度。

class Solution {
    public int maxDepth(TreeNode root) {
        LinkedList<TreeNode> list = new LinkedList<>();
        if(root != null) list.add(root);
        int dept = 0;
        while(!list.isEmpty()){
            int size = list.size();
            for(int i = 0;i < size;i++){
                TreeNode node = list.pollFirst();
                if(node.left != null) list.addLast(node.left);
                if(node.right != null) list.addLast(node.right);
            }
            dept++;
        }
        return dept;
    }
}

1 声望1 粉丝

引用和评论

0 条评论