Given a complete binary tree, count the number of nodes.
Note:
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.
Example:
Input:1/ \2 3/ \ /4 5 6Output: 6
题意
统计完全二叉树中的结点个数。
思路
不考虑完全二叉树性质的话,可以直接用递归处理。
如果考虑完全二叉树的性质,可以如下操作:沿着左子树一直走得到最左边的高度leftHeight,沿着右子树一直走得到最右边的高度rightHeight,如果两者相等,说明当前树正好是满二叉树,可以直接计算得到结点个数;如果leftHeight > rightHeight,说明当前树是非满完全二叉树,递归处理左右子树即可。
上述方法还可以进一步优化,使其每一次递归时只需要向一边递归,而不需要同时向两边递归(类似于二分查找):计算左子树的高度leftHeight和右子树的高度rightHeight,如果两者相等,说明左子树是满二叉树,可以直接计算结点数,而右子树是完全二叉树(可能是满二叉树),只需要向右子树递归即可;如果leftHeight > rightHeight,说明右子树是满二叉树,而左子树是完全二叉树,只需要向左子树递归即可。
代码实现 - 递归
class Solution {public int countNodes(TreeNode root) {return root == null ? 0 : 1 + countNodes(root.left) + countNodes(root.right);}}
代码实现 - 完全二叉树 1
class Solution {public int countNodes(TreeNode root) {int leftHeight = 0, rightHeight = 0;// 求最左边的高度TreeNode x = root;while (x != null) {leftHeight++;x = x.left;}// 求最右边的高度x = root;while (x != null) {rightHeight++;x = x.right;}if (leftHeight == rightHeight) {return (1 << leftHeight) - 1;} else {return 1 + countNodes(root.left) + countNodes(root.right);}}}
代码实现 - 完全二叉树 2
class Solution {public int countNodes(TreeNode root) {if (root == null) {return 0;}int leftHeight = getHeight(root.left);int rightHeight = getHeight(root.right);if (leftHeight == rightHeight) {return 1 + (1 << leftHeight) - 1 + countNodes(root.right);} else {return 1 + (1 << rightHeight) - 1 + countNodes(root.left);}}private int getHeight(TreeNode x) {return x == null ? 0 : 1 + getHeight(x.left);}}
参考
