Description:
Given a complete binary tree, count the number of nodes.
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 2hnodes inclusive at the last level h.
思路:给一颗完全二叉树求其节点的个数。首先要明确完全二叉树的定义:把满二叉树从上到下,从左到右进行编号,完全二叉树是其中编号没有断续的部分。也就是说完全二叉树只可能在最右子树的叶子节点的位子上有空缺。而且左右子树的高度差不能大于1。所以只要是count(左节点)==count(右节点)那么就是一颗满二叉树。可以用公式计算出节点的个数NodeCount=2^h - 1。若不是满二叉树的话就递归遍历求count(左子树) + count(右子树) + 1。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int countNodes(TreeNode root) { if(root==null) return 0; TreeNode left = root, right = root; int leftCount = 0; while(left!= null) { left = left.left; leftCount ++; } int rightCount = 0; while(right != null) { right = right.right; rightCount ++; } if(leftCount==rightCount) { return (2<<(leftCount-1)) - 1; } else { return countNodes(root.left) + countNodes(root.right) + 1; } } }