222. Count Complete Tree Nodes
Problem:
Given a complete binary tree, count the number of nodes.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Analysis:
This problem has nothing to do with binary search. The key is to compare the height of root's left and right tree. If left == right, it's simple, number of nodes is pow(2, h) - 1. Otherwise, countNodes(root.left) + countNodes(root.right) + 1
Solution:
Calculating height from root to left and only root.left are both ok. The latter one requires null check as follows.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int countNodes(TreeNode root) { if (root == null) return 0; int left = leftHeight(root.left); int right = rightHeight(root.right); return left == right ? (1 << (left + 1)) - 1 : countNodes(root.left) + countNodes(root.right) + 1; } int leftHeight(TreeNode root) { if (root == null) return 0; return 1 + leftHeight(root.left); } int rightHeight(TreeNode root) { if (root == null) return 0; return 1 + rightHeight(root.right); } }
评论
发表评论