树的非递归遍历

本文介绍了二叉树的三种遍历方法:先序、中序和后序遍历,并提供了详细的C++实现代码。先序遍历首先访问根节点,然后遍历左子树,最后遍历右子树;中序遍历则先遍历左子树,再访问根节点,最后遍历右子树;后序遍历先遍历左右子树,最后访问根节点。

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

1.先序(我只把这些当模板)

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> res;
        if(root==NULL)return res;
        stack<TreeNode*> ms;
        TreeNode* p=root;
        while(!ms.empty()||p)
        {
            if(p)
            {
                res.push_back(p->val);
                ms.push(p);
                p=p->left;
            }
            else if(!ms.empty())
            {
                p=ms.top();
                ms.pop();
                if(p)p=p->right;
            }
        }
        return res;
    }
};


2.中序

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        if(root==NULL)return res;
        stack<TreeNode*> ms;
        TreeNode* p=root;
        while(!ms.empty()||p)
        {
            if(p)
            {
                ms.push(p);
                p=p->left;
            }
            else
            {
                p=ms.top();
                res.push_back(p->val);
                ms.pop();
                p=p->right;
            }
        }
        return res;
    }
};



3.后序

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        if(root==NULL)return res;
        stack<TreeNode*> ms;
        TreeNode *p=root,*pre=NULL;
        while(!ms.empty()||p)
        {
            if(p)
            {
                ms.push(p);
                p=p->left;
            }
            else
            {
                p=ms.top();
                if(p->right!=NULL&&p->right!=pre)p=p->right;
                else 
                {
                    res.push_back(p->val);
                    ms.pop();
                    pre=p;
                    p=NULL;
                }
            }
        }
        return res;
    }
};




看看大神的代码(以下代码来源于leetcode)

1.先序(看起来很优美)

class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
    if (root==NULL) {
        return vector<int>();
    }
    vector<int> result;
    stack<TreeNode *> treeStack;
    treeStack.push(root);
    while (!treeStack.empty()) {
        TreeNode *temp = treeStack.top();
        result.push_back(temp->val);
        treeStack.pop();
        if (temp->right!=NULL) {
            treeStack.push(temp->right);
        }
        if (temp->left!=NULL) {
            treeStack.push(temp->left);
        }
    }
    return result;
}
};



2.中序( o(1)空间复杂度)

Morris traversal

 
 

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        if(root == null) return new ArrayList<Integer>();
        List<Integer> res = new ArrayList<Integer>();
        TreeNode pre = null;
        while(root != null){
        	if(root.left == null){
        		res.add(root.val);
        		root = root.right;
        	}else{
        		pre = root.left;
        		while(pre.right != null && pre.right != root){
        			pre = pre.right;
        		}
        		if(pre.right == null){
        			pre.right = root;
        			root = root.left;
        		}else{
        			pre.right = null;
        			res.add(root.val);
        			root = root.right;
        		}
        	}
        }
        return res;
    }
}


3.后序(美得不敢直视)

vector<int> postorderTraversal(TreeNode *root) {
    vector<int> v;
    if (!root) return v;
    
    stack<TreeNode *> s;
    s.push(root);
    
    TreeNode *p = NULL;
    while(!s.empty()) {
        p = s.top();
        s.pop();
        v.insert(v.begin(), p->val);
        if (p->left) s.push(p->left);
        if (p->right) s.push(p->right);
    }
    
    return v;
}




### 关于二叉排序非递归遍历的实现 #### 中序遍历(In-order Traversal) 中序遍历是一种常见的二叉排序遍历方式,其访问节点的顺序为:先访问左子,再访问当前节点,最后访问右子。以下是基于栈的非递归中序遍历算法: ```c++ void InOrderTraversal(BSTree root) { std::stack<BSTNode*> s; BSTNode* p = root; while (p != nullptr || !s.empty()) { while (p != nullptr) { s.push(p); // 将左子压入栈 p = p->lchild; } if (!s.empty()) { p = s.top(); // 访问栈顶节点 s.pop(); printf("%d ", p->key); // 输出节点值 p = p->rchild; // 转向右子 } } } ``` 上述代码通过显式使用栈来模拟递归调用的过程[^1]。 --- #### 前序遍历(Pre-order Traversal) 前序遍历按照“根 -> 左 -> 右”的顺序访问节点。以下是其实现方法: ```c++ void PreOrderTraversal(BSTree root) { std::stack<BSTNode*> s; BSTNode* p = root; if (root == nullptr) return; s.push(root); while (!s.empty()) { p = s.top(); s.pop(); printf("%d ", p->key); // 输出当前节点值 if (p->rchild != nullptr) { s.push(p->rchild); // 先压入右孩子 } if (p->lchild != nullptr) { s.push(p->lchild); // 后压入左孩子 } } } ``` 此代码利用栈实现了前序遍历逻辑[^2]。 --- #### 后序遍历(Post-order Traversal) 后序遍历遵循“左 -> 右 -> 根”的访问顺序。由于后序遍历较为复杂,通常需要两个栈或者标记已访问过的节点。以下是单栈版本的实现: ```c++ void PostOrderTraversal(BSTree root) { std::stack<BSTNode*> s1, s2; BSTNode* p = root; if (root == nullptr) return; s1.push(root); while (!s1.empty()) { p = s1.top(); s1.pop(); s2.push(p); // 存储到第二个栈中反转顺序 if (p->lchild != nullptr) { s1.push(p->lchild); // 先处理左子 } if (p->rchild != nullptr) { s1.push(p->rchild); // 再处理右子 } } while (!s2.empty()) { p = s2.top(); s2.pop(); printf("%d ", p->key); // 按照逆序输出 } } ``` 该算法借助双栈机制完成后序遍历操作[^3]。 --- #### 层次遍历(Level Order Traversal) 层次遍历按层依次访问节点,适合采用队列数据结构实现: ```c++ #include <queue> void LevelOrderTraversal(BSTree root) { std::queue<BSTNode*> q; if (root == nullptr) return; q.push(root); while (!q.empty()) { BSTNode* p = q.front(); q.pop(); printf("%d ", p->key); // 输出当前节点值 if (p->lchild != nullptr) { q.push(p->lchild); // 加入左子 } if (p->rchild != nullptr) { q.push(p->rchild); // 加入右子 } } } ``` 以上代码展示了如何使用队列进行广度优先搜索以完成层次遍历。 --- ### 总结 不同类型的遍历适用于不同的场景需求。例如,在验证二叉排序性质时常用中序遍历;而在某些特定应用下可能更倾向于其他形式的遍历
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值