//二叉树的遍历,所谓的前中后,其实就是根节点相对于左右节点的
//访问时间,前就是根左右,中就是左根右,后就是左右根
//递归形式的前序遍历
void PreSearch(TreeNode* head){
if (head){
cout << head->val;
PreSearch(head->left);
PreSearch(head->right);
}
}
//非递归形式的前序遍历,用vector模拟一个栈
//一般递归的非递归形式都是以栈来实现的。
//几条技巧:如果是后压栈的状态,相当于一个递归函数
void PreSearch1(TreeNode* head){
if (!head) return;
vector<TreeNode*> s(100);
s[0] = head;
int top = 1;
while (top){
TreeNode* node = s[--top];
cout << node->val;
if (node->right) s[top++] = node->right;
if (node->left) s[top++] = node->left;
}
cout << endl;
}
//非递归形式前序遍历第二种方法,尾递归的优化
//只将右子树放入栈,减少了入栈出栈次数。
void PreSearch2(TreeNode* head){
if (!head) return;
vector<TreeNode*> s(100); //vector和top模拟栈
int top = 0;
TreeNode* p = head;
//一个技巧,栈首元素为0,为了下面的while准备
while (p){
cout << p->val;
if (p->right) s[++top] = p->right;
//p可以是当前节点的左子树,如果左子树为0,p为弹栈顶元素
//这时候体现出了s[0]=0的作用,如果p=0,说明栈为空&&左子树为空。
p = p->left ? p->left : s[top--];
}
cout << endl;
}
二叉树的前序遍历非递归形式
最新推荐文章于 2024-01-30 09:00:13 发布