首页 > 其他 > 详细

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

时间:2020-03-16 20:12:06      阅读:102      评论:0      收藏:0      [点我收藏+]

中序遍历:

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;
    }
};

 

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

原文:https://www.cnblogs.com/olajennings/p/12505370.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!