//前序遍历:结点右孩子先入栈,左孩子后入栈,空结点不入栈
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> result;
if(root == NULL) return result;
st.push(root);
while(!st.empty()){
TreeNode *node = st.top();
st.pop();
result.push_back(node->val);
if(node->right) st.push(node->right); //先入栈右结点
if(node->left) st.push(node->left);
}
return result;
}
//后序遍历:结点左孩子先入栈,右孩子后入栈,空结点不入栈。并且将结果数组反转
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> result;
if(root == NULL) return result;
st.push(root);
while(!st.empty()){
TreeNode *node = st.top();
st.pop();
result.push_back(node->val);
if(node->left) st.push(node->left);//先入栈左结点
if(node->right) st.push(node->right);
}
reverse(result.begin(),result.end()); //反转结果数组
return result;
}
//中序遍历:用指针来访问结点,用栈来保存中间结点
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> result;
TreeNode* cur = root;
while(!st.empty()||cur!=NULL){
if(cur!=NULL){
st.push(cur);
cur = cur->left; //一直往左走,走到头
}else{
cur = st.top(); 弹出中间结点
st.pop();
result.push_back(cur->val);
cur = cur->right;
}
}
return result;
}
//层序遍历:队列实现
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> que;
vector<vector<int>> result;
if(root != NULL) que.push(root);
while(!que.empty()){
int quesize = que.size();
vector <int> v;
while(quesize--){
TreeNode* node = que.front();
que.pop();
v.push_back(node->val);
if(node->left){
que.push(node->left);
}
if(node->right){
que.push(node->right);
}
}
result.push_back(v);
}
return result;
}
二叉树的前、中、后、层序的非递归遍历C++
最新推荐文章于 2024-11-12 13:55:23 发布