前序遍历
144. 二叉树的前序遍历 - 力扣(LeetCode)
递归
class Solution {
private:vector<int> res;
public:void backing(TreeNode* root){if(!root) return;res.push_back(root->val);if(root->left) backing(root->left);if(root->right) backing(root->right);}vector<int> preorderTraversal(TreeNode* root) {backing(root);return res;}
};
非递归
由于前序遍历的顺序是,根->左->右,故而使用一个栈保存临时元素时,需要先压入右节点,再压入左节点,这样取出元素的时候就可以按照正确顺序取出
class Solution {
public:vector<int> preorderTraversal(TreeNode* root) {stack<TreeNode*> st;//使用一个栈用于保存临时节点vector<int> res;//保存结果if(!root) return res;//若树为空,则直接返回st.push(root);while(!st.empty()){ //取出栈顶节点TreeNode* node=st.top();st.pop();//访问res.push_back(node->val);//先压入右节点,再压入左节点if(node->right) st.push(node->right);if(node->left) st.push(node->left);}return res;}
};
中序遍历
94. 二叉树的中序遍历 - 力扣(LeetCode)
递归
class Solution {
private:vector<int> res;
public:void backing(TreeNode* root){if(!root) return;if(root->left) backing(root->left);res.push_back(root->val);if(root->right) backing(root->right);}vector<int> inorderTraversal(TreeNode* root) {backing(root);return res;}
};
非递归
class Solution {
public:vector<int> inorderTraversal(TreeNode* root) {stack<TreeNode*> st;vector<int> res;if(!root) return res;TreeNode* cur=root;while(cur || !st.empty()){while(cur){st.push(cur);cur=cur->left;}cur=st.top();st.pop();res.push_back(cur->val);cur=cur->right;}return res;}
};
后序遍历
145. 二叉树的后序遍历 - 力扣(LeetCode)
递归
class Solution {
private:vector<int> res;
public:void backing(TreeNode* root){if(!root) return;if(root->left) backing(root->left);if(root->right) backing(root->right);res.push_back(root->val);}vector<int> postorderTraversal(TreeNode* root) {backing(root);return res;}
};
非递归
此处借用了一个技巧,我们知道前序遍历的顺序是根->左->右,那么如果我们将遍历顺序调整为根->右->左,最后再将结果的顺序倒过来,就变成了左->右->根,也就是后序遍历的顺序
class Solution {
public:vector<int> postorderTraversal(TreeNode* root) {stack<TreeNode*> st;vector<int> res;if(!root) return res;//先遍历出根->右->左的顺序结果st.push(root);while(!st.empty()){TreeNode* node=st.top();st.pop();res.push_back(node->val);if(node->left) st.push(node->left);if(node->right) st.push(node->right);}//将根->右->左的顺序结果倒过来之后,就变成了左->右->根的遍历顺序reverse(res.begin(),res.end());return res;}
};