222. Count Complete Tree Nodes -- 求完全二叉树节点个数
2016-04-21 15:30
621 查看
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.
1. 递归
2. 非递归
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.
1. 递归
//return -1 if it is not. int isCompleteTree(TreeNode* root) { if (!root) return 0; int cnt = 1; TreeNode *left = root, *right = root; for(; left && right; left=left->left, right=right->right) { cnt *= 2; } if (left!=NULL || right!=NULL) { return -1; } return cnt-1; } int countNodes(TreeNode* root) { int cnt = isCompleteTree(root); if (cnt != -1) return cnt; int leftCnt = countNodes(root->left); int rightCnt = countNodes(root->right); return leftCnt + rightCnt + 1; }
2. 非递归
/** * 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 ans = 0, lh = 0, rh = 0; TreeNode *p = root; while(p) { //先求p的左右子树的最大深度。若相等,则p加左子树节点个数为1<<lh,再求右子树;若不等,则p加右子树节点个数为1<<rh,再求左子树。 if(!lh) //若lh不为0,说明lh由之前的lh--得到,是已知的。 { for(TreeNode *t = p->left; t; t = t->left) lh++; } for(TreeNode *t = p->right; t; t = t->left) rh++; if(lh == rh) { ans += 1 << lh; p = p->right; } else { ans += 1 << rh; p = p->left; } lh--; rh = 0; } return ans; } };
相关文章推荐
- 116. Populating Next Right Pointers in Each Node
- Node.js
- Cisco VPP(5) node关系图
- node入门解读(grunt,npm)
- nodejs高大上的部署方式-PM2
- nodejs部署
- 数据上传
- node express 304 avoid
- Node+Express+Jade
- 24. Swap Nodes in Pairs
- nodejs从对象中随机选times个对象的初始化问题
- mbed 初试(LinkNode 板卡)(2016-04-21)
- Nodejs in Visual Studio Code 10.IISNode
- 24. Swap Nodes in Pairs
- Grunt集成自动重启
- Leetcode——populating-next-right-pointers-in-each-node
- nodejs 里面执行 es6 的语法语句
- NodeJS 单线程 和java 多线程
- Windows环境下使用Node.js
- 如何利用Node.js 构建分布式集群