1、二叉树的递归遍历
1.1、前序遍历
144. 二叉树的前序遍历 - 力扣(LeetCode)
class Solution {
public:
void ergodic(TreeNode* cur, vector<int>& vec) {
// 终止条件
if (cur == NULL) return ;
// 存根结点
vec.push_back(cur->val);
// 递归左子树
ergodic(cur->left, vec);
// 递归右子树
ergodic(cur->right, vec);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
ergodic(root, result);
return result;
}
};
1.2、中序遍历
94. 二叉树的中序遍历 - 力扣(LeetCode)
class Solution {
public:
void ergodic(TreeNode *cur, vector<int>& vec) {
if (cur == NULL) return ;
ergodic(cur->left, vec);
// 对比先序遍历的顺序
vec.push_back(cur->val);
ergodic(cur->right, vec);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
ergodic(root, result);
return result;
}
};
1.3、后序遍历
145. 二叉树的后序遍历 - 力扣(LeetCode)
class Solution {
public:
void ergodic(TreeNode *cur, vector<int> &vec) {
if (cur == NULL) return ;
ergodic(cur->left, vec);
ergodic(cur->right, vec);
vec.push_back(cur->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
ergodic(root, result);
return result;
}
};
2、迭代法
2.1、先序遍历
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
// 用栈压入元素
stack<TreeNode*> mystack;
vector<int> result;
if (root == NULL) return result;
mystack.push(root);
while (!mystack.empty()) {
TreeNode *temp = mystack.top();
result.push_back(temp->val);
mystack.pop();
// 先压入right,后压入left,后进先出
if (temp->right != NULL) mystack.push(temp->right);
if (temp->left != NULL) mystack.push(temp->left);
}
return result;
}
};
2.2、后序遍历
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> mystack;
vector<int> result;
if (root == NULL) return result;
mystack.push(root);
while (!mystack.empty()) {
TreeNode* temp = mystack.top();
mystack.pop();
result.push_back(temp->val);
if (temp->left != NULL) mystack.push(temp->left);
if (temp->right != NULL) mystack.push(temp->right);
}
// reverse(result.begin(), result.end());
for (int i = 0, j = result.size() - 1; i < j; i++, j--) {
swap(result[i], result[j]);
}
return result;
}
};
2.3、中序遍历
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
// 设立指针
TreeNode* cur = root;
while (cur != NULL || !st.empty()) {
if (cur != NULL) {
st.push(cur);
cur = cur->left;
} else {
cur = st.top();
st.pop();
result.push_back(cur->val);
cur = cur->right;
}
}
return result;
}
};