leetcode-94. 二叉树的中序遍历

时间:2021-07-26 16:33:12   收藏:0   阅读:0

我的菜鸡方法C++实现普通二叉树的中序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> midseq;
        if(root == nullptr) return midseq;
        stack<TreeNode *> s;
        TreeNode *p=nullptr;
        p=root;
        while(!s.empty()  || p != nullptr){
            while(p != nullptr){  //left child is exist 
                s.push(p);
                p=p->left;
            }
            if(!s.empty()){ //output left or root node to queue
                p=s.top();
                s.pop();
                midseq.push_back(p->val);
                p=p->right;
            }
        }
        return midseq;
    }
};
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!