1. 程式人生 > >222. Count Complete Tree Nodes - Medium

222. Count Complete Tree Nodes - Medium

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 6

Output: 6

 

思路:比較左右子樹深度是否相等,如果相等,返回2 ^ h - 1;不等則對左右子節點遞迴。因為是complete tree,求左右子樹的深度只要一直往左/右走並計數即可

time: O(logn * logn), space: O(n) worst case, O(logn) best case

/**
 * 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 leftDepth = depth(root, true); int rightDepth = depth(root, false); if(leftDepth == rightDepth) { return (1 << leftDepth) - 1; }
else { return 1 + countNodes(root.left) + countNodes(root.right); } } public int depth(TreeNode node, boolean isLeft) { int depth = 0; while(node != null) { node = isLeft ? node.left : node.right; depth++; } return depth; } }