二叉樹的中序遍歷(非遞歸)

/**
 * 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) {
        vector<int>res;
        if(root==NULL) return res;
        stack<TreeNode*>st;
        TreeNode *cur=root;
        while(cur||!st.empty()){
            while(cur!=NULL){
                st.push(cur);
                cur=cur->left;
            }
            if(!st.empty()){
                res.push_back(st.top()->val);
                cur=st.top()->right;
                st.pop();
            }
        }
        return res;
        
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章