二叉树的递归遍历
- 递归三部曲
- 1.确定递归函数的参数和返回值 2.确定终止条件 3.确定单层的递归逻辑
- 前中后序遍历只需要改一下位置即可
class Solution {
public:vector<int> inorderTraversal(TreeNode* root) {vector<int> vec;traversal(root, vec);return vec;}void traversal(TreeNode* cur, vector<int>& vec) {if (cur == nullptr) {return;}traversal(cur->left, vec);vec.push_back(cur->val);traversal(cur->right, vec);}
};
二叉树的迭代遍历
- 利用栈的特性
- 栈是先进后出,所以遍历左右节点的时候需要反过来
class Solution {
public:vector<int> inorderTraversal(TreeNode* root) {stack<TreeNode*> st;vector<int> result;if (root == nullptr) {return result;}st.push(root);while (!st.empty()) {TreeNode* cur = st.top();if (cur != nullptr) {st.pop();if (cur->right)st.push(cur->right);st.push(cur);st.push(nullptr);if (cur->left)st.push(cur->left);} else {st.pop();cur = st.top();st.pop();result.push_back(cur->val);}}return result;}
};
二叉树的层序遍历
class Solution {
public:vector<vector<int>> levelOrder(TreeNode* root) {queue<TreeNode*> que;vector<vector<int>> result;if (root == nullptr) {return result;}que.push(root);while (!que.empty()) {int size = que.size();vector<int> vec;for (int i = 0; i < size; i++) {TreeNode* node = que.front();que.pop();vec.push_back(node->val);if (node->left)que.push(node->left);if (node->right)que.push(node->right);}result.push_back(vec);}return result;}
};
层序遍历刷题