1. 二叉树的前序遍历
- 题目描述
二叉树的前、中、后序遍历的递归写法类似,后面就不写了。
- 递归实现
class Solution {
public:
vector<int> res;
void dfs(TreeNode *root) {
if(root == nullptr)
return;
res.push_back(root->val);
dfs(root->left);
dfs(root->right);
}
vector<int> preorderTraversal(TreeNode* root) {
dfs(root);
return res;
}
};
- 非递归实现
用栈实现,注意在迭代过程中先压右再压左,出栈时才能先出左再出右。
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(root == nullptr) return res;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()) {
TreeNode* tmp = st.top();
st.pop();
res.push_back(tmp->val);
if(tmp->right)
st.push(tmp->right);
if(tmp->left)
st.push(tmp->left);
}
return res;
}
};
2. 二叉树的中序遍历
- 题目描述
- 非递归
先处理左子树,再处理右边,但根的左子树的右子树优先级高于根的右子树,要注意压栈顺序
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> st;
auto p = root;
while(p || !st.empty()) {
while(p) {
st.push(p);
p = p->left;
}
auto t = st.top();
st.pop();
res.push_back(t->val);
p = t->right;
}
return res;
}
};
3. 二叉树的后序遍历
- 题目描述
- 非递归实现
后序可以利用前序来记忆,后序相当于前序的一个“逆序”,只不过前序需要变一下:
前序变成根右左
,再逆序就是后序左右根
了。
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()) {
auto t = st.top();
st.pop();
res.push_back(t->val);
if(t->left)
st.push(t->left);
if(t->right)
st.push(t->right);
}
reverse(res.begin(), res.end());
return res;
}
};
4. 二叉树的层序遍历
- 题目描述
- 代码
使用队列,先计算深度把空间开辟好,再根据层数push_back即可。
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
int d = depth(root);
vector<vector<int>> res(d);
if(!root) return res;
queue<pair<TreeNode*, int>> q;
q.push(make_pair(root, 0));
while(!q.empty()) {
auto t = q.front();
q.pop();
auto node = t.first;
int index = t.second;
res[index].push_back(node->val);
if(node->left)
q.push(make_pair(node->left, index + 1));
if(node->right)
q.push(make_pair(node->right, index + 1));
}
return res;
}
int depth(TreeNode *root) {
if(!root) return 0;
int l = depth(root->left), r = depth(root->right);
return (l > r ? l : r) + 1;
}
};