[LeetCode]Binary Tree Inorder Traversal

本文详细介绍了如何将二叉树的递归中序遍历转换为迭代版本,通过使用栈来模拟递归过程,从而避免了栈溢出的风险并提高了代码效率。
struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
//recursive to iterative, we always need stack
//thought of the stack of recursive function, then we can come
//up with the iterative version easily. 
//turn recursive into iterative
//if(root), s.push(root)(save the scene, just like function stack), root=root->left(get to the next level, called by function itself)
//if(!root), set root=s.top()(get the nearest scene) visit its value and then set root=root->right(get to the next level, called by function itself)

public:
	vector<int> inorderTraversal(TreeNode *root) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		vector<int> res;
		stack<TreeNode*> s;
		TreeNode* current = root;
		while (true)
		{
			//add all left in
			if(current)
			{
				s.push(current);
				current = current->left;
			}
			else
			{
				if(s.empty())
					break;
				current = s.top();
				s.pop();
				res.push_back(current->val);
				current = current->right;
			}

		}
		return res;
	}
};

second time

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        stack<TreeNode*> nodeS;
        TreeNode* cur = root;
        vector<int> ans;
        while(true)
        {
            if(cur != NULL)
            {
                nodeS.push(cur);
                cur = cur->left;    
            }
            else
            {
                if(!nodeS.empty())
                {
                    ans.push_back(nodeS.top()->val);
                    cur = nodeS.top()->right;
                    nodeS.pop();
                }
                else break;//terminate case
            }
        }
        return ans;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI记忆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值