Leetcode 222.完全二叉树的节点个数
题目要求
示例 1:

输入:root = [1,2,3,4,5,6]
输出:6
示例 2:
输入:root = []
输出:0
示例 3:
输入:root = [1]
输出:1
后序遍历统计个数
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
|
class Solution { public int countNodes(TreeNode root) { if (root == null) return 0; int count = postOrder(root); return count; } public int postOrder(TreeNode root ) { if (root == null) return 0; int left = postOrder(root.left); int right = postOrder(root.right); return left + right + 1; } }
class Solution { public int countNodes(TreeNode root) { if(root == null) { return 0; } return countNodes(root.left) + countNodes(root.right) + 1; } }
|
完全二叉树特性
满二叉树n层节点个数为(假设根节点为第一层):2n−1
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
| class Solution {
public int countNodes(TreeNode root) { if (root == null) return 0; TreeNode left = root.left; TreeNode right = root.right; int leftDepth = 0, rightDepth = 0;
while (left != null) { left = left.left; leftDepth++; } while (right != null) { right = right.right; rightDepth++; } if (leftDepth == rightDepth) { return (2 << leftDepth) - 1; } return countNodes(root.left) + countNodes(root.right) + 1; } }
|