描述
222. 完全二叉树的节点个数 - 力扣(Leetcode)
分析
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| import java.util.Queue; import java.util.LinkedList;
public class CountCompleteTreeNodes222 { public static void main(String[] args){ Integer[] arr = new Integer[]{1,2,3,4,5,6}; TreeNode node = MyUtils.buildTree(arr); int res = new Solution().countNodes(node); System.out.println("这颗完全二叉树的节点个数为:" + res); } }
class Solution {
public int countNodes(TreeNode root) { if (root == null) return 0; TreeNode leftNode = root.left, rightNode = root.right; int leftDepth = 0, rightDepth = 0; while(leftNode != null){ leftNode = leftNode.left; leftDepth++; } while(rightNode != null){ rightNode = rightNode.right; rightDepth++; } if (leftDepth == rightDepth) { return (2 << leftDepth) - 1; } return countNodes(root.left) + countNodes(root.right) + 1; } public int countNodes1(TreeNode root) { if (root == null) return 0; Queue<TreeNode> que = new LinkedList<>(); que.offer(root); int counts = 0, size; while(!que.isEmpty()){ size = que.size(); TreeNode temp; for (int i = 0; i < size; i++) { temp = que.poll(); counts++; if(temp.left != null) que.offer(temp.left); if (temp.right != null) que.offer(temp.right); } } return counts; } public int countNodes2(TreeNode root) { if(root == null) return 0; return countNodes2(root.left) + countNodes2(root.right) + 1; }
}
class TreeNode { int val; TreeNode left; TreeNode right;
public TreeNode(){}; public TreeNode(int val){this.val = val;} public TreeNode(int val, TreeNode left, TreeNode right){ this.val = val; this.left = left; this.right = right; } }
class MyUtils {
public static TreeNode buildTree(Integer[] arr) { return buildTreeHelper(arr, 0); }
public static TreeNode buildTreeHelper(Integer[] arr, Integer index) { if (index >= arr.length || arr[index] == null) { return null; }
TreeNode node = new TreeNode(arr[index]);
node.left = buildTreeHelper(arr, 2 * index + 1); node.right = buildTreeHelper(arr, 2 * index + 2);
return node; } }
|
总结
实现 |
时间复杂度 |
备注 |
完全二叉树玩法 |
O(lgn*lgn) |
关键就是(满二叉树) 节点数 = (2 << leftDepth) - 1 |
层序遍历 |
O(n) |
层序遍历的写法 |
递归 |
O(n) |
两行代码 |