【LeetCode】—— C++实现二叉树的遍历(非递归)

34 篇文章 1 订阅
34 篇文章 3 订阅

一、二叉树的前序遍历LeetCode144题

题目描述及解析可参考博客 https://blog.csdn.net/chenxiyuehh/article/details/86931798
基本思路均相同,只是实现语言不同,C++比C语言实现要简单的多,毕竟可以直接使用vector和stack,不用像C语言一样还得自己实现一个栈,也可以将遍历序列直接存入vector中,而不用像C语言一样要遍历两遍二叉树,第一遍为确定为遍历序列开辟多大空间的数组,第二遍才是将遍历序列存入数组中。

代码实现

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> preV;
        if(root == NULL)
            return preV;
        stack<TreeNode*> st;
	TreeNode* cur = root;
	while (st.empty() != 1 || cur != NULL)
	{
		// 1.访问坐路节点并入栈
		while (cur != NULL)
		{
            preV.push_back(cur->val);
			st.push(cur);

			cur = cur->left;
		}

		struct TreeNode* top = st.top();
		st.pop();

		// 子问题:访问右子树
		cur = top->right;
	}
	return preV;  
    }
};

二、二叉树的中序遍历Leetcode94题

代码实现

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> inV;
        if(root == NULL)
            return inV;
        
        TreeNode* cur = root;
        stack<TreeNode*> st;
        while(st.empty() != 1 || cur != NULL)
        {
            while(cur != NULL)
            {
                st.push(cur);
                cur = cur->left;
            }
            TreeNode* top = st.top();
            inV.push_back(top->val);
            st.pop();
            
            //子问题,访问左路结点的右子树
            cur = top->right;
        }
        return inV;
    }
};

三、二叉树的后序遍历LeetCode145题

代码实现

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> postV;
        if(root == NULL)
            return postV;
        TreeNode* cur = root;
        TreeNode* prev = NULL;//定义一个指针指向cur的前一个位置
        
        stack<TreeNode*> st;
        while(st.empty() != 1 || cur != NULL)
        {
            //访问左路结点并入栈
            while(cur != NULL)
            {
                st.push(cur);
                cur = cur->left;
            }
            TreeNode* top = st.top();
            if(top->right == NULL || top->right == prev)
            {
                postV.push_back(top->val);
                st.pop();
                prev = top;
            }
            else
            {
                //子问题,访问左路结点的右子树
                cur = top->right;
            }
        }
        return postV;
        
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值