https://leetcode.com/problems/count-complete-tree-nodes/
宽度优先搜索方法,超时!!
/** * 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: int countNodes(TreeNode* root) { int height=1; if(root==NULL) return 0; TreeNode * temp=root; stack<TreeNode *> s1; while(temp!=NULL) { height++; s1.push(temp); temp=temp->right; } int count=(int)(pow(2,height)-1); bool flag=0; int len=1; int leftVal=0; int rightVal=0; while(!s1.empty()) { len++; TreeNode * temp=s1.top(); s1.pop(); if(right==0) rightVal=getCount(temp->right); else rightVal=leftVal+right+1; leftVal=getCount(temp->left); if(leftVal!=rightVal) break; } int lack=(int)(pow(2,len)-1-(leftVal+rightVal+1)); int res=count-lack; return res; } int getCount(TreeNode * node) { if(node==NULL) return 0; int res=0; queue<TreeNode *> q; q.push(node); while(!q.empty()) { res++; TreeNode * temp=q.front(); q.pop(); if(temp->left!=NULL) q.push(temp->left); if(temp->right!=NULL) q.push(temp->right); } return res; } };