二叉树day5

559. N 叉树的最大深度

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

//迭代层序
// class Solution {
//     public int maxDepth(Node root) {
//         Deque<Node> queue = new LinkedList<>();
//         int depth = 0;
//         if (root != null) queue.offer(root);
//         while (!queue.isEmpty()) {
//             depth++;
//             int size = queue.size();
//             for (int i = 0; i < size; i++) {
//                 Node cur = queue.poll();
//                 for (Node child : cur.children) {
//                     if (child != null) queue.offer(child);
//                 }
//             }
//         }
//         return depth;
//     }
// }

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

//将树看成多个满二叉树的组合
class Solution {
    public int countNodes(TreeNode root) {
        if (root == null) return 0;
        TreeNode left = root.left, right = root.right;
        int leftH = 0, rightH = 0;
        while (left != null) {
            leftH++;
            left = left.left;
        }
        while (right != null) {
            rightH++;
            right = right.right;
        }
        //满二叉树
        if (leftH == rightH) return ((2 << leftH) - 1);
        else return countNodes(root.left) + countNodes(root.right) + 1;
    }
}
//递归层序列
// class Solution {
//     public int countNodes(TreeNode root) {
//         if(root == null) {
//             return 0;
//         }
//         return countNodes(root.left) + countNodes(root.right) + 1;
//     }
// }

//层序 O(n)
// class Solution {
//     public int countNodes(TreeNode root) {
//         Deque<TreeNode> queue = new LinkedList<>();
//         int res = 0;
//         if (root != null) queue.offer(root);
//         while (!queue.isEmpty()) {
//             TreeNode cur = queue.poll();
//             res++;
//             if (cur.left != null) queue.offer(cur.left);
//             if (cur.right != null) queue.offer(cur.right);
//         }
//         return res;
//     }
// }

参考:programmercarl.com

posted @ 2022-03-31 21:43  一梦两三年13  阅读(23)  评论(0)    收藏  举报