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;
    }
}

猜你喜欢

转载自www.cnblogs.com/fatttcat/p/10242309.html