前序遍历
/* * 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> ret; stack<TreeNode *> stk; if (!root) return ret; while (root || stk.size()) { if (root) { stk.push(root); ret.push_back(root->val); root = root->left; } else { root = stk.top(); stk.pop(); root = root->right; } } return ret; } };
中序遍历
/* * 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> ret; stack<TreeNode *> stk; if (!root) return ret; while (root || stk.size()) { if (root) { stk.push(root); root = root->left; } else { root = stk.top(); stk.pop(); ret.push_back(root->val); root = root->right; } } return ret; } };
后序遍历
/* * 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> ret; stack<TreeNode *> stk; if (!root) return ret; TreeNode *last = nullptr; while (root || stk.size()) { if (root) { stk.push(root); root = root->left; } else { TreeNode *now = stk.top(); if (now->right && last != now->right) root = now->right; else { ret.push_back(now->val); stk.pop(); last = now; } } } return ret; } };