题目一:二叉树的前序遍历
给定一个二叉树,返回它的前序遍历
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [1,2,3]
代码实现如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> v;
if(root == nullptr){
return v;
}
if(root != nullptr){
//先将跟压到栈中
st.push(root);
while(!st.empty()){
TreeNode* cur = st.top();
//取出根并将根尾插到vector中
v.push_back(cur->val);
st.pop();
//先将cur->right压到栈中
if(cur->right){
st.push(cur->right);
}
//再将cur->left压到栈中,此时cur->left再栈顶,下次取出
//cur->left尾插到vector中,当左子树全部被取完,然后取右子
//树
if(cur->left){
st.push(cur->left);
}
}
}
return v;
}
};
题目二:二叉树的中序遍历
给定一个二叉树,返回它的中序遍历。
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [1,3,2]
代码实现如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> v;
TreeNode* p = root;
if(nullptr == root){
return v;
}
if(nullptr != root){
while(p != nullptr || !st.empty()){
//p不为空,压入栈中,p走左子树,将左子树全部压到栈中
while(p != nullptr){
//先压根
st.push(p);
p = p->left;
}
//取出栈顶元素给p,并将栈顶元素取出插入到vector中
p = st.top();
v.push_back(p->val);
st.pop();
//取出p->right压到栈中
p = p->right;
}
}
return v;
}
};
题目三:二叉树的后序遍历
给定一个二叉树,返回它的后序遍历。
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [3,2,1]
用两个栈和递归实现二叉树的后续遍历。
代码实现如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> s1;
stack<TreeNode*> s2;
vector<int> res;
if(!root){
return res;
}
s1.push(root);
while(!s1.empty()){
TreeNode* cur = s1.top();
s1.pop();
s2.push(cur);
//先将left压到栈里,再将right压到栈里,然后取出将右子树压到s2
//中,最后再压左子树
//待右子树全部压完,然后将左子树全部压到栈s2中
//此时栈s2从上到下依次是左子树、右子树、根
if(cur->left){
s1.push(cur->left);
}
//后压右子树,然后全部将有子树压到栈s2中
if(cur->right){
s1.push(cur->right);
}
}
while(!s2.empty()){
//弹出s2栈顶元素,依次尾插到vector中,最终得到二叉树的后序
//遍历
res.push_back(s2.top()->val);
s2.pop();
}
return res;
}
};