94.二叉树的中序遍历

在这里插入图片描述
迭代算法:

/**
 * 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> inorderTraversal(TreeNode* root) {
        TreeNode* p=root;
        stack<TreeNode*> s;
        vector<int> v;
        while(p||!s.empty())
        {
            while(p)
            {
                s.push(p);
                p=p->left;
            }
           if(!s.empty())
            {
                p=s.top();
                s.pop();
                v.push_back(p->val);
                p=p->right;
            }
        }
        return v;
    }
};
发布了90 篇原创文章 · 获赞 7 · 访问量 2179

猜你喜欢

转载自blog.csdn.net/weixin_43784305/article/details/103016446