LeetCode

来源:互联网 发布:sql中union的用法 编辑:程序博客网 时间:2024/06/14 12:21

94.二叉树中根遍历

非递归方法是有必要掌握的,递归思路比较好想,非递归,就是为啥自己老是绕不过去。

/** * 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> ans;        if (!root) return ans;        unordered_map<TreeNode*, bool> vis;        stack<TreeNode*> s;        s.push(root);        while (!s.empty()) {            TreeNode* cur = s.top();            if (cur->left && vis.find(cur) == vis.end()) {                s.push(cur->left);                vis[cur] = true;            }            else {                ans.push_back(cur->val);                s.pop();                if (cur->right) s.push(cur->right);            }        }        return ans;    }};

144.二叉树先根遍历

/** * 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> ans;        stack<TreeNode*> s;        if (root == NULL) return ans;        s.push(root);        while (!s.empty()) {            TreeNode* cur = s.top();            ans.push_back(cur->val);            s.pop();            if (cur->right) s.push(cur->right);            if (cur->left) s.push(cur->left);        }        return ans;    }};


145.二叉树后根遍历

跟先跟遍历一样,用map存了是否访问过

/** * 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> ans;        if (!root) return ans;        stack<TreeNode*> s;        unordered_map<TreeNode*, bool> vis;        s.push(root);        while (!s.empty()) {            TreeNode* cur = s.top();            if (cur->right && vis.find(cur->right) == vis.end()) {                s.push(cur->right);                vis[cur->right] = true;            }            if (cur->left && vis.find(cur->left) == vis.end()) {                s.push(cur->left);             vis[cur->left] = true;               }            if (cur == s.top()) {                ans.push_back(cur->val);                s.pop();            }         }        return ans;    }};