二叉树的前序、中序、后序、层次遍历——颜色标记法

中序遍历:

class Solution {
public:
    typedef pair<TreeNode*, int> colorNode;
    vector<int> inorderTraversal(TreeNode* root) {
        int white = 0;
        int gray = 1;
        stack<colorNode> nodeStack;
        
        TreeNode* node = root;
        int color = white;
        
        nodeStack.push(colorNode(node, color));
        
        vector<int> output;
        
        while(!nodeStack.empty()){
            node = nodeStack.top().first;
            color = nodeStack.top().second;
            nodeStack.pop();
            if(node == NULL) continue;
            if(color == white){
                nodeStack.push(colorNode(node->right,white));
                nodeStack.push(colorNode(node,gray));
                nodeStack.push(colorNode(node->left,white));
            }
            else{
                output.emplace_back(node->val);
            }
        }
        
        return output;
    }
};

 

posted @ 2020-03-16 17:44  jenningszheng  阅读(506)  评论(0编辑  收藏  举报