刷题日记14 | 111. 二叉树的最小深度、559. N 叉树的最大深度、222. 完全二叉树的节点个数

85 阅读1分钟

刷题日记14

559. N 叉树的最大深度

层序遍历

class Solution {
    public int maxDepth(Node root) {
        int depth = 0;
        if(root == null) return depth;
        Queue<Node> q = new LinkedList<>();
        q.offer(root);
        while(!q.isEmpty()){
            depth++;
            int len = q.size();
            while(len-- > 0){
                Node node = q.poll();
                for(Node c : node.children){
                    q.offer(c);
                }
            }
        }
        return depth;
    }
}

递归遍历(后序遍历)

class Solution {
    public int maxDepth(Node root) {
        int depth = 0;
        if(root == null) return depth;
        for(Node n : root.children){
            depth = Math.max(depth, maxDepth(n));
        }
        return depth+1;
    }
}

111. 二叉树的最小深度

层序遍历

class Solution {
    public int minDepth(TreeNode root) {
        if(root == null) return 0;
        int depth = 0;
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while(!q.isEmpty()){
            depth++;
            int len = q.size();
            while(len-- > 0){
                TreeNode node = q.poll();
                if(node.left != null) q.offer(node.left);
                if(node.right != null) q.offer(node.right);
                if(node.left == null && node.right == null){
                    return depth;
                }
            }
        }
        return depth;
    }
}

递归法(后序遍历)

class Solution {
    public int minDepth(TreeNode root) {
        if(root == null) return 0;
        int depth = 0;
        int leftDepth = minDepth(root.left); //左
        int rightDepth = minDepth(root.right); //右
        if(root.left == null) return rightDepth + 1; //中
        if(root.right == null) return leftDepth + 1; //中
        return Math.min(leftDepth, rightDepth) + 1;
    }
}

222. 完全二叉树的节点个数

递归法(后序遍历)

class Solution {
    public int countNodes(TreeNode root) {
        if(root == null) return 0;
        int left = countNodes(root.left);
        int right = countNodes(root.right);
        return left + right + 1;
    }
}

层序遍历

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