Count Complete Tree Nodes
生活随笔
收集整理的這篇文章主要介紹了
Count Complete Tree Nodes
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
https://leetcode.com/problems/count-complete-tree-nodes/
寬度優(yōu)先搜索方法,超時!!
/*** 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);elserightVal=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;} };?
轉(zhuǎn)載于:https://www.cnblogs.com/aguai1992/p/4780452.html
總結(jié)
以上是生活随笔為你收集整理的Count Complete Tree Nodes的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎么加强泰山风景区的安全管理和应急预案?
- 下一篇: 触发器初接触-同步两个表的指定字段