先序

class Solution {
public:
    void dfs(TreeNode* root,vector<int>& v)
    {
        stack<TreeNode*>s;
        while(root||!s.empty())
        {
            while(root!=NULL)
            {
                s.push(root);
                v.push_back(root->val);
                root = root->left;
            }
            root = s.top();
            s.pop();
            root = root->right;
        }
    }
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int>v;
        if(root)
            dfs(root,v);
        return v;
    }
};

中序

class Solution {
public:
    void dfs(TreeNode* root,vector<int>& v)
    {
        stack<TreeNode*>s;
        while(root||!s.empty())
        {
            while(root!=NULL)
            {
                s.push(root);
                root = root->left;
            }
            root = s.top();
            s.pop();
            v.push_back(root->val);
            root = root->right;
        }
    }
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int>v;
        if(root)
            dfs(root,v);
        return v;
    }
};

后序

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int>v;
        if(root==NULL)
            return v;
        stack<TreeNode*>s;
        s.push(root);
        while(!s.empty())
        {
            TreeNode* node=s.top();
            s.pop();
            v.push_back(node->val);
            if(node->left!=NULL)
                s.push(node->left);
            if(node->right!=NULL)
                s.push(node->right);
        }
        for(int i=0,j=v.size()-1;i<j;i++,j--)
            swap(v[i],v[j]);
        return v;
    }
};

相关文章:

  • 2021-11-19
  • 2022-12-23
  • 2022-01-14
  • 2021-12-03
  • 2021-12-03
  • 2021-09-23
  • 2021-12-03
  • 2021-11-20
猜你喜欢
  • 2021-10-14
  • 2021-04-07
  • 2021-11-30
  • 2021-11-20
  • 2021-10-21
  • 2021-11-09
  • 2021-12-03
相关资源
相似解决方案