二叉树的遍历(前序、中序和后序),递归和非递归的实现。前序和中序实现基本类似,后序稍微复杂一点,需要判断当前节点的右子树是否为空或者已经访问过,代码如下:
//前序遍历:递归
void preorder(TreeNode *root, vector<int> &path)
{
if(root != NULL)
{
path.push_back(root->val);
preorder(root->left, path);
preorder(root->right, path);
}
}
//中序遍历:递归
void inorder(TreeNode *root, vector<int> &path)
{
if(root != NULL)
{
inorder(root->left, path);
path.push_back(root->val);
inorder(root->right, path);
}
}
//后续遍历:递归
void postorder(TreeNode *root, vector<int> &path)
{
if(root != NULL)
{
postorder(root->left, path);
postorder(root->right, path);
path.push_back(root->val);
}
}
//前序遍历:非递归
void preorderTraversal(TreeNode *root, vector<int> &path)
{
stack<TreeNode *> s;
TreeNode *p = root;
while(p != NULL || !s.empty())
{
while(p != NULL)
{
path.push_back(p->val);
s.push(p);
p = p->left;
}
if(!s.empty())
{
p = s.top();
s.pop();
p = p->right;
}
}
}
//中序遍历:非递归
void inorderTraversal(TreeNode *root, vector<int> &path)
{
stack<TreeNode *> s;
TreeNode *p = root;
while(p != NULL || !s.empty())
{
while(p != NULL)
{
s.push(p);
p = p->left;
}
if(!s.empty())
{
p = s.top();
path.push_back(p->val);
s.pop();
p = p->right;
}
}
}
//后序遍历:非递归第一种
void postorderTraversal1(TreeNode *root, vector<int> &path)
{
stack<TempNode *> s;
TreeNode *p = root;
TempNode *temp;
while(p != NULL || !s.empty())
{
while(p != NULL) //沿左子树一直往下搜索,直至出现没有左子树的结点
{
TempNode *tempNode = new TempNode;
tempNode->btnode = p;
tempNode->isFirst = true;
s.push(tempNode);
p = p->left;
}
if(!s.empty())
{
temp = s.top();
s.pop();
if(temp->isFirst == true) //表示是第一次出现在栈顶
{
temp->isFirst = false;
s.push(temp);
p = temp->btnode->right;
}
else //第二次出现在栈顶
{
path.push_back(temp->btnode->val);
p = NULL;
}
}
}
}
//后序遍历:非递归第二种
void postorderTraversal2(TreeNode *root, vector<int> &path)
{
stack<TreeNode *> s;
TreeNode *curr = NULL;
TreeNode *last = NULL;
s.push(root);
while(!s.empty())
{
curr = s.top();
if((curr->lchild == NULL && curr->rchild == NULL) ||
(last != NULL && (last == curr->lchild || last == curr->rchild)))
{
path.push_back(curr->val);
s.pop();
last = curr;
}
else
{
if(curr->rchild != NULL)
s.push(curr->rchild);
if(curr->lchild != NULL)
s.push(curr->lchild);
}
}
}