标签:
1.打印二叉树
程序很简单,但是其中犯了一个小错误,死活找不到,写代码要注意啊
这里左右子树,要注意是node->left,结果写成root->left
vector<int> PrintFromTopToBottom(TreeNode *root) { vector<int> res; if (NULL == root) return res; TreeNode* node; deque<TreeNode*> tmp; tmp.push_back(root); while (tmp.size()) { node = tmp.front(); res.push_back(node->val); tmp.pop_front(); if (node->left) tmp.push_back(node->left); if (node->right) tmp.push_back(node->right); } return res; }
2.求1+2+...+n
class A{ public: A(){ ++n;sum+=n; } static int getsum(){ return sum; } static void reset(){ n=0;sum=0; } ~A(){} private: static int n; static int sum; }; int A::n=0; int A::sum=0; class Solution { public: int Sum_Solution(int n) { A::reset(); //必不可少,测试集会重复运行 A* tmp=new A[n]; delete[] tmp; return A::getsum(); } };
3.二叉树镜像
class Solution { public: void Mirror(TreeNode *pRoot) { if(NULL==pRoot||(NULL==pRoot->left&&NULL==pRoot->right)) return; mirrorset(pRoot); } void mirrorset(TreeNode* root){ if(NULL==root||(NULL==root->left&&NULL==root->right)) return; TreeNode *tmp=root->left; root->left=root->right; root->right=tmp; if(root->left) mirrorset(root->left); if(root->right) mirrorset(root->right); } };
标签:
原文地址:http://www.cnblogs.com/jason1990/p/4733206.html