判断两个( float )变量是否相等以及和 0 值比较方法
int main(int argc, char *argv[])
{
float x = 0.000f;
const float EPSINON = 1e-6;
if (( x >= -EPSINON ) && ( x <= EPSINON ))
{
printf("x 是零\n");
}
指针和引用的区别
★ 相同点:
1. 都是地址的概念;
指针指向一块内存,它的内容是所指内存的地址;引用是某块内存的别名。
★ 区别:
1. 指针是一个实体,而引用仅是个别名;
2. 引用使用时无需解引用(*),指针需要解引用;
3. 引用只能在定义时被初始化一次,之后不可变;指针可变;
引用“从一而终” ^_^
4. 引用没有 const,指针有 const,const 的指针不可变;
5. 引用不能为空,指针可以为空;
6. “sizeof 引用”得到的是所指向的变量(对象)的大小,而“sizeof 指针”得到的是指针本身(所指向的变量或对象的地址)的大小;
typeid(T) == typeid(T&) 恒为真,sizeof(T) == sizeof(T&) 恒为真,
但是当引用作为成员时,其占用空间与指针相同(没找到标准的规定)。
7. 指针和引用的自增(++)运算意义不一样;
利用层次遍历非递归求二叉树高度
/**
* 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 maxDepth(TreeNode* root) {
//return maxDepthWithLevelTraversal(root);
return maxDepthRecursion(root);
}
/* 递归版本 */
int maxDepthRecursion(TreeNode* root){
int HL, HR, MaxH;
if (root){
HL = maxDepth(root->left);
HR = maxDepth(root->right);
MaxH = (HL > HR) ? HL : HR;
return MaxH + 1;
}
else
return 0;
}
/* 层次遍历的非递归版本 */
int maxDepthWithLevelTraversal(TreeNode* root){
/* 判断树是否为空 */
if(!root){
return 0;
}
int height = 0; // 初始化树的高度为0
queue<TreeNode*>Q; // 初始化一个队列,并将根节点入队
Q.push(root);
/* 当队列不为空时 */
/* 实际上当每次循环开始时,队列中存储的刚好是将要访问下一层的所有元素*/
while(!Q.empty()){
height++;
int curLevelSize = Q.size(); // 记录当前层元素个数
int cnt = 0;
/* 弹出当前层所有元素 */
while(cnt < curLevelSize){
TreeNode* temp = Q.front();
Q.pop();
cnt++;
/* 将下一层的元素入队列 */
if(temp->left){
Q.push(temp->left);
}
if(temp->right){
Q.push(temp->right);
}
}
}
return height;
}
};