94. 二叉树的中序遍历

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> st;
        while(root||st.size())
        {
            while(root)
            {
                st.push(root);
                root=root->left;
            }
            //此时root为空,返回根节点并输出,然后遍历右孩子
            //栈一定有元素,两个while循环保证了
            root=st.top();
            st.pop();
            res.push_back(root->val);
            root=root->right; 
        }
        return res;
    }
};
posted @ 2023-05-21 15:05  穿过雾的阴霾  阅读(11)  评论(0)    收藏  举报