1. 層序遍歷二叉樹
C++ 代碼
vector<vector<int> > levelTraversal(TreeNode* pRoot) { // 層序遍歷二叉樹
vector<vector<int> > result;
if(pRoot != NULL) {
queue<TreeNode*> q;
q.push(pRoot);
int levelWith = 0;
int n = 1;
vector<int> v;
while(!q.empty()) {
TreeNode* p = q.front();
v.push_back(p->val);
if(p->left) {
q.push(p->left);
++levelWith;
}
if(p->right) {
q.push(p->right);
++levelWith;
}
q.pop();
--n;
if(0 == n) {
result.push_back(v);
v.resize(0);
n = levelWith;
levelWith = 0;
}
}
}
return result;
}
2. 之字形遍歷二叉樹
C++ 代碼
vector<vector<int> > zigzag(TreeNode* pRoot) {// 按之字形順序遍歷二叉樹
vector<vector<int> > result;
if(NULL == pRoot) return result;
stack<TreeNode*> s1/*從右到左壓入*/, s2/*從左到右壓入*/;
s1.push(pRoot);
vector<int> vec;
while(!s1.empty() || !s2.empty()) {
while(!s1.empty()) {
TreeNode* node = s1.top();
vec.push_back(node->val);
if(node->left)
s2.push(node->left);
if(node->right)
s2.push(node->right);
s1.pop();
}
result.push_back(vec);
vec.resize(0);
while(!s2.empty()) {
TreeNode* node = s2.top();
vec.push_back(node->val);
if(node->right)
s1.push(node->right);
if(node->left)
s1.push(node->left);
s2.pop();
}
result.push_back(vec);
vec.resize(0);
}
return result;
}