码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ 222. Count Complete Tree Nodes

时间:2016-11-12 11:16:09      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:完全二叉树   which   ast   cep   under   can   possible   pre   tween   

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.

 

Subscribe to see which companies asked this question

解答

这道题目因为是完全二叉树,所以求节点数时可以做一下优化,当恰好全部充满时直接计算节点数,而不是继续用递归……否则有个点会过不去……

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int countNodes(struct TreeNode* root) {
    int level = 0;
    struct TreeNode *node_1 = root, *node_2 = root;
    
    while(NULL != node_1&&NULL != node_2){
        node_1 = node_1->left;
        node_2 = node_2->right;
        level++;
    }
    if(NULL != node_1){
        return countNodes(root->left) + countNodes(root->right) + 1;
    }
    else{
        return pow(2, level) - 1;
    }
}

 

LeetCode OJ 222. Count Complete Tree Nodes

标签:完全二叉树   which   ast   cep   under   can   possible   pre   tween   

原文地址:http://www.cnblogs.com/YuNanlong/p/6033698.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!