原题链接在这里:https://leetcode.com/problems/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.
题解:
Complete Tree的定义是左右深度差不大于1.
递归调用函数,终止条件两个,一个是root == null, return 0. 另一个是左右高度相同说明是满树, return 2^height-1.
若是左右高度不同,递归调用求 左子树包含Node数 + 右子树包含Node数 + 1(自身).
Note:1. 用Math.pow(), 注意arguments 和 return type 都是double, 此处会TLE.
2. 用<<来完成幂运算,但注意<<的precedence比+,-还要低,需要加括号.
Time Complexity: O(h^2). worst case对于每一层都要求一遍当前点到leaf得深度.
假设只有最底层多了一个TreeNode 那么计算height就需要每层计算一遍h + (h-1) + (h-2) + ... + 1 = O(h^2).
Space: O(h), stack space.
AC Java:
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 if(root == null){ 13 return 0; 14 } 15 TreeNode p = root; 16 TreeNode q = root; 17 int leftDepth = 0; 18 int rightDepth = 0; 19 while(p!=null){ 20 leftDepth++; 21 p = p.left; 22 } 23 while(q!=null){ 24 rightDepth++; 25 q = q.right; 26 } 27 28 if(leftDepth == rightDepth){ 29 return (1<<leftDepth) - 1; 30 }else{ 31 return countNodes(root.left) + 1 + countNodes(root.right); 32 } 33 } 34 }