222. Count Complete Tree Nodes
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.
本题要求完全二叉树的节点个数,这里我们可以采用二分搜索的方法来做,二叉树的特点是每个非叶子节点都可以分成三部分,一部分是本身节点,一个是左子树,一个是右子树,我们先做一个方法函数来求一个树的高度,然后分别求出该树的高度和其右子树的高度(如果右子树非空),如果右子树的高度等于该树的高度-1,则说明该树的左子树部分是满的,则可以将其左子树的节点树和+递归其右子树;代码如下:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int height(TreeNode root){ 12 return root==null?-1:1+height(root.left); 13 } 14 public int countNodes(TreeNode root) { 15 int h = height(root); 16 return h<0?0:height(root.right)==h-1?(1<<h)+countNodes(root.right):(1<<h-1)+countNodes(root.left); 17 } 18 } 19 // the run time complexity could be O(loglogn) this is because evey recision will take a height function ,will take longn time,and we have logn steps so the totl run time complexity could be loglogn;the space compexity could be logn;
下面采用的是迭代的方法,代码如下:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int height(TreeNode node){ 12 return node==null?-1:1+height(node.left); 13 } 14 public int countNodes(TreeNode root) { 15 int nodes = 0; 16 int h = height(root); 17 while(root!=null){ 18 if(height(root.right)==h-1){ 19 nodes+=(1<<h); 20 root = root.right; 21 h = height(root); 22 }else{ 23 nodes+=(1<<h-1); 24 root = root.left; 25 h = height(root); 26 } 27 } 28 return nodes; 29 } 30 }
还有一种做法就是,创建两个TreeNode,left和right,当right不为空的时候,左子树一直遍历其左孩子,右子树一直遍历其右孩子,当right为空的时候,左面也为空,则说明没有下一行并且该行是满的;如果左面不为空,则递归其root的左子树和右子树;代码如下:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int countNodes(TreeNode root) { 12 int height = 0; 13 TreeNode left = root; 14 TreeNode right = root; 15 while(right!=null){ 16 height++; 17 left = left.left; 18 right = right.right; 19 } 20 if(left==null) return (1<<height)-1; 21 return 1+countNodes(root.left)+countNodes(root.right); 22 } 23 }