1:分别用递归和非递归方式实现二叉树的前序、中序和后序遍历
class Solution{
public:
//递归方式依次实现二叉树前序、中序、后序遍历
void preOrder(TreeNode *root,vector<int>&vector){
if(root!=NULL){
vector.emplace_back(root->val);
preOrder(root->left,vector);
preOrder(root->right,vector);
}
}
void inOrder(TreeNode *root,vector<int>&vector){
if(root!=NULL){
inOrder(root->left,vector);
vector.emplace_back(root->val);
inOrder(root->right,vector);
}
}
void postOrder(TreeNode *root,vector<int>&vector){
if(root!=NULL){
postOrder(root->left,vector);
postOrder(root->right,vector);
vector.emplace_back(root->val);
}
}
//非递归方式实现先序、中序、后序遍历
void preOrderUnRecur(TreeNode *root,vector<int>&vector){
if(root==NULL)return;
stack<TreeNode*>stack;
stack.emplace(root);
while (!stack.empty()){
TreeNode *node=stack.top();
stack.pop();
vector.emplace_back(node->val);
//按照右左的顺序压入节点,这样弹出时就是根->左->右
if(node->right!=NULL)
stack.push(node->right);
if(node->left!=NULL)
stack.push(node->left);
}
}
//利用栈实现非递归中序遍历
void inOrderUnRecur(TreeNode *root,vector<int>&vector){
if(root==NULL)return;
stack<TreeNode*>stack;
while (!stack.empty()||root!=NULL){
if(root!=NULL){//栈空
stack.push(root);
root=root->left;//将左子树压入栈,只有root为NULL才取遍历右子树,左中右
}
else{
root=stack.top();
stack.pop();
vector.emplace_back(root->val);
root=root->right;
}
}
}
//利用两个栈实现后序非递归遍历
void postOrderUnRecur1(TreeNode *root,vector<int>&vector){
if(root==NULL)return;
stack<TreeNode*>A;
stack<TreeNode*>B;
A.push(root);//加入A中
while (!A.empty()){
root=A.top();
A.pop();
B.push(root);//A中节点依次弹出放入B中
if(root->left!=NULL)
A.push(root->left);
if(root->right!=NULL)
A.push(root->right);
}
while (!B.empty()){
vector.push_back(B.top()->val);
B.pop();
}
}
//利用单个栈实现二叉树后序遍历
void postOrderUnRecur2(TreeNode *root,vector<int>&vector){
if(root==NULL)return;
stack<TreeNode*>stack;
stack.push(root);
TreeNode *temp=NULL;
while (!stack.empty()){
temp=stack.top();
if(temp->left!=NULL&&root!=temp->left&&root!=temp->right)
stack.push(temp->left);
else if(temp->right!=NULL&&root!=temp->right)
stack.push(temp->right);
else{
vector.push_back(stack.top()->val);
stack.pop();
root=temp;
}
}
}
};
2:较为直观地打印二叉树