二叉树
144 二叉树的前序遍历
问题描述
给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
每一层访问顺序:根左右
终止条件:current_node == NULL
递归
注意:
(1) 递归的参数及返回值;
(2) 终止条件;
(3) 每一层要做什么。
class Solution {
public:
void traverse(TreeNode* cur, vector<int>& vec)
{
if (cur == NULL) return;
vec.push_back(cur->val);
traverse(cur->left, vec);
traverse(cur->right, vec);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
traverse(root, res);
return res;
}
};
迭代,利用栈
为了按照左右顺序输出,在栈中的存放顺序应为右左。【栈的特性】
//前序遍历:迭代、栈
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
if (root == NULL) return res;
st.push(root);//栈
while (!st.empty())
{
TreeNode* node = st.top();//找到当前根结点
st.pop();//栈:当前根结点出栈
res.push_back(node->val);//更新res
if (node->right) st.push(node->right);//栈:非空右结点入栈
if (node->left) st.push(node->left);//栈:非空左结点入栈
}
return res;
}
};
94 二叉树的中序遍历
问题描述
给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。
访问顺序:左根右
递归
//中序遍历:递归
class Solution {
public:
void inorder(TreeNode* root,vector<int>& res)
{
if(root == nullptr)
{
return;
}
inorder(root->left,res);
res.push_back(root->val);
inorder(root->right,res);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
inorder(root,res);
return res;
}
};
迭代,利用栈
//中序遍历:迭代、栈
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
if (root == NULL) return res;
TreeNode* cur = root;
while (!st.empty() || cur != NULL)
{
if (cur != NULL)
{
st.push(cur);
cur = cur->left;
}
else
{
cur = st.top();
st.pop();
res.push_back(cur->val);
cur = cur->right;
}
}
return res;
}
};
145 二叉树的后序遍历
问题描述
给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。
访问顺序:左右根
递归
class Solution {
public:
void traverse(TreeNode* cur, vector<int>& vec)
{
if (cur == NULL) return;
traverse(cur->left, vec);
traverse(cur->right, vec);
vec.push_back(cur->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
traverse(root, res);
return res;
}
};
迭代,利用栈
巧妙地使用了翻转函数,后序的访问顺序为左右根,翻转顺序为根右左,可以通过修改前序根左右。
//后序遍历:迭代、栈
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
if (root == NULL) 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;
}
};