二叉树的前、中、后序遍历(非递归)

【二叉树的前序遍历】

传送门

/**
 * 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> preorderTraversal(TreeNode* root) {
        vector<int> outcome;
        stack<TreeNode*>tree;
        if(root!=nullptr)
        tree.push(root);
        while(!tree.empty())
        {
            TreeNode*t=tree.top();
            tree.pop();
            if(t!=nullptr)
            {
                if(t->right)
                tree.push(t->right);
                if(t->left)
                tree.push(t->left);
                tree.push(t);
                tree.push(nullptr);
            }
            else
            {
                outcome.push_back(tree.top()->val);
                tree.pop();
            }
        }
        return outcome;
    }
};

【二叉树的中序遍历】

传送门

/**
 * 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>outcome;
        stack<TreeNode*>tree;
        if(root!=nullptr)
        tree.push(root);
        while(!tree.empty())
        {
            
            TreeNode*t=tree.top();
            tree.pop();
           if(t!=nullptr)
           {
                if(t->right)
                 tree.push(t->right);
                tree.push(t);
                tree.push(nullptr);
                 if(t->left)
                 tree.push(t->left);

           }
           else
           {
               outcome.push_back(tree.top()->val);
               tree.pop();
           }
        }
        return outcome;
        
    }
};

【二叉树的后序遍历】

传送门

/**
 * 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> postorderTraversal(TreeNode* root) {
        vector<int> outcome;
        stack<TreeNode*> tree;
        if(root!=nullptr)
            tree.push(root);
        while(!tree.empty())
        {
            TreeNode*t=tree.top();
            tree.pop();
            if(t!=nullptr)
            {
                
                tree.push(t);
                tree.push(nullptr);
                if(t->right)
                tree.push(t->right);
                 if(t->left)
                tree.push(t->left);
                
               
            }
            else
            {
                outcome.push_back(tree.top()->val);
                tree.pop();
            }
        }
        return outcome;
    }
};

你可能感兴趣的:(LeetCode,leetcode,二叉树,stack)