二叉树遍历

前序遍历

class Solution {
public:
    vector preorderTraversal(TreeNode* root) {
        stack str;
        vector ptr;
        if(root==NULL)
        {
            return ptr;
        }   
        str.push(root);
        while(!str.empty())
        {
            TreeNode* cur=str.top();
            ptr.push_back(cur->val);
            str.pop();            
            if(cur->right)
            {
                str.push(cur->right);
            }
            if(cur->left)
            {
                str.push(cur->left);
            }
        }
        return ptr;        
    }
};

中序遍历

class Solution {
public:
    vector inorderTraversal(TreeNode* root) {
        stack str;
        vector ptr;        
        if(!root)
            return ptr;       
        TreeNode* cur=root;
        while(cur||!str.empty())
        {
            while(cur)
            {
                str.push(cur);
                cur=cur->left;
            }            
            if(!str.empty())
            {
                cur=str.top();
                ptr.push_back(cur->val);
                str.pop();
                cur=cur->right;
            }
        }     
        return ptr;      
    }
};

后续遍历

class Solution {
public:
    vector postorderTraversal(TreeNode* root) {
        stack str;
        vector ptr;
        TreeNode* next;
        TreeNode* cur;      
        cur=root;
        next=NULL;
                
        while(cur||!str.empty())
        {
            while(cur)
            {
                str.push(cur);
                cur=cur->left;
            }         
            cur=str.top();
            if(cur->right==NULL || cur->right==next)
            {
                ptr.push_back(cur->val);
                next=cur;
                str.pop();
                cur=NULL;
            }
            else
            {
                cur=cur->right;
            }
        }
        return ptr;        
    }
};

层序遍历

你可能感兴趣的:(数据结构)