Stack的应用——Binary Tree Preorder Traversal

本文介绍了一种使用迭代法实现二叉树前序遍历的算法。通过利用栈来辅助处理节点访问顺序,该方法避免了递归带来的额外开销,并详细展示了具体的实现步骤与源代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:

给定一个二叉树,返回其节点值的前序遍历。采用迭代的方法。

解题思路:

前序遍历的法则是:


访问一个节点;
访问它的左子树;
访问它的右子树;


根据法则可以得到如下算法:


访问当前节点是否有左子树

if 有左子树     

    访问左子树的根节点值

    if 有右子树    

        将右子树的根节点压入栈

    ptr更新为左子树的根节点

else if没有左子树有右子树

    访问右子树的根节点值

    ptr更新为右子树的根节点

else 为叶节点

    if 栈不空

        访问栈顶的节点值

        弹出栈顶元素

    else 

        跳出循环


源代码如下:

/**

 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) 
    {
        vector<int> result;
        stack<TreeNode*> stk;
        TreeNode* ptr=root;
        if(root==NULL) return result;
        else result.push_back(ptr->val);
        while(true)
        {
            if(ptr->left!=NULL)
            {
                result.push_back(ptr->left->val);
                if(ptr->right!=NULL) stk.push(ptr->right);
                ptr=ptr->left;
            }
            else if(ptr->right!=NULL)
            {
                result.push_back(ptr->right->val);
                ptr=ptr->right;
            }
            else
            {
                if(!stk.empty())
                {
                    ptr=stk.top();
                    result.push_back(ptr->val);
                    stk.pop();
                }
                else
                    break;
            }
        }
        return result;
    }
};
### 顺序存储二叉树的前序、中序和后序遍历非递归算法 #### 背景说明 顺序存储二叉树通常采用数组形式实现,其中父节点 `i` 的左子节点位于索引位置 `2*i+1`,右子节点位于索引位置 `2*i+2`。基于此特性,可以利用栈模拟递归过程完成前序、中序和后序遍历。 以下是具体的非递归实现代码: --- #### 前序遍历(Preorder Traversal) 前序遍历遵循 **根 -> 左 -> 右** 的顺序。通过栈保存未访问过的节点,并优先访问其左子节点。 ```c #include <stdio.h> #include <stdlib.h> #define MAX_SIZE 100 typedef struct { int data[MAX_SIZE]; int top; } Stack; void initStack(Stack *s) { s->top = -1; } int isEmpty(Stack *s) { return s->top == -1; } void push(Stack *s, int value) { if (s->top >= MAX_SIZE - 1) { printf("Stack Overflow\n"); exit(1); } s->data[++(s->top)] = value; } int pop(Stack *s) { if (isEmpty(s)) { printf("Stack Underflow\n"); exit(1); } return s->data[(s->top)--]; } // Preorder traversal of a binary tree stored in an array void preorder(int *tree, int size) { if (!tree || size <= 0) return; Stack stack; initStack(&stack); int i = 0; // Start from the root node at index 0 while (i < size || !isEmpty(&stack)) { while (i < size && tree[i] != -1) { // Traverse to the leftmost child printf("%d ", tree[i]); push(&stack, i); // Push current index onto the stack i = 2 * i + 1; // Move to the left child } if (!isEmpty(&stack)) { i = pop(&stack); // Backtrack one level up i = 2 * i + 2; // Move to the right child } } } ``` --- #### 中序遍历(Inorder Traversal) 中序遍历遵循 **左 -> 根 -> 右** 的顺序。同样借助栈保存路径上的节点,在回溯过程中依次访问这些节点。 ```c // Inorder traversal of a binary tree stored in an array void inorder(int *tree, int size) { if (!tree || size <= 0) return; Stack stack; initStack(&stack); int i = 0; // Start from the root node at index 0 while (i < size || !isEmpty(&stack)) { while (i < size && tree[i] != -1) { // Traverse to the leftmost child push(&stack, i); // Push current index onto the stack i = 2 * i + 1; // Move to the left child } if (!isEmpty(&stack)) { i = pop(&stack); // Visit the parent node after all its left children are visited printf("%d ", tree[i]); i = 2 * i + 2; // Move to the right child } } } ``` --- #### 后序遍历(Postorder Traversal) 后序遍历遵循 **左 -> 右 -> 根** 的顺序。为了简化逻辑,引入额外标记变量记录当前状态。 ```c // Postorder traversal of a binary tree stored in an array using two stacks void postorder(int *tree, int size) { if (!tree || size <= 0) return; Stack stack1, stack2; initStack(&stack1); initStack(&stack2); push(&stack1, 0); // Start with the root node while (!isEmpty(&stack1)) { int i = pop(&stack1); // Pop and move it to another stack push(&stack2, i); if (2 * i + 1 < size && tree[2 * i + 1] != -1) { push(&stack1, 2 * i + 1); // Push left child first } if (2 * i + 2 < size && tree[2 * i + 2] != -1) { push(&stack1, 2 * i + 2); // Then push right child } } while (!isEmpty(&stack2)) { int i = pop(&stack2); printf("%d ", tree[i]); // Print nodes in reverse order } } ``` --- ### 总结 以上实现了顺序存储二叉树的前序、中序和后序遍历非递归版本[^1][^2][^3]。每种遍历方式的核心在于如何合理使用栈来控制访问次序以及处理左右子节点的关系。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值