222.leetcode.Count Complete Tree Nodes(medium)[完全二叉树 节点个数]

来源:互联网 发布:张红兵 知乎 编辑:程序博客网 时间:2024/05/04 07:09

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.

题目中完全二叉树的最大的节点是满二叉树的时候为2^h-1(h为高度,根节点为1)。采用暴力破解对整棵树遍历一遍会超时,最后利用完全二叉树的特点,首先遍历左子树的左子树得到这棵树的左子树最大高度,同理找到右子树的右子树的最大高度,如果两者相等那么说明是一棵满二叉树可以直接得到答案。否则的话把问题分而治之,那么对左右子树分别求节点数再加上根节点的节点个数1.

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    //计算完全二叉树的节点数,下面是暴力破解的方式,遍历一遍整棵树    /*void countNodes(TreeNode* root,int &n)    {        if(root != NULL) ++n;        else return;        countNodes(root->left,n);        countNodes(root->right,n);        return;    }    int countNodes(TreeNode* root) {        if(root == NULL) return 0;        int n = 0;        countNodes(root,n);        return n;    }*/    int getHeight1(TreeNode *root)    {        if(root == NULL) return 0;        int n = 1;        while(root->left != NULL){ n++; root = root->left;}        return n;    }    int getHeight2(TreeNode *root)    {        if(root == NULL) return 0;        int n = 1;        while(root->right != NULL){ n++; root = root->right;}        return n;    }    int countNodes(TreeNode* root) {        if(root == NULL) return 0;        int lheight = getHeight1(root->left);        int rheight = getHeight2(root->right);        if(lheight == rheight)             return pow(2,1+lheight)-1;        else            return countNodes(root->left)+countNodes(root->right)+1;    }};


0 0
原创粉丝点击