leetcode + 求完全二叉树的节点数目,递归,BFS超时间

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013554860/article/details/79948191
点击打开链接
class Solution {
public:
    int countNodes(TreeNode* root) {
        int hLeft=0, hRight=0;
        TreeNode *pLeft = root, *pRight = root;
        while (pLeft) {
            hLeft+=1;
            pLeft = pLeft->left;
        }
        while (pRight) {
            hRight+=1;
            pRight = pRight->right;
        }
        if(hLeft==hRight) return pow(2,hRight)-1;
        return countNodes(root->left)+countNodes(root->right)+1; //必须用root
    }
};
class Solution {
public:
    queue<TreeNode*> Q;
    int BFS(TreeNode* root)
    {
        if(root==NULL) return 0;
        TreeNode *temple1=NULL;
        int result =0;
        Q.push(root); result+=1;
        while (!Q.empty()) {
            temple1 =Q.front(); Q.pop();
            if(temple1->left){
                Q.push(temple1->left);
                result+=1;
            }
            if(temple1->right){
                Q.push(temple1->right);
                result+=1;
            }
        }
        return result;
    }
    int countNodes(TreeNode* root) {
        return BFS(root);
    }


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页