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;
}