描述
94. 二叉树的中序遍历
给定一个二叉树的根节点 root ,返回它的 中序 遍历。
示例 1:
输入:root = [1,null,2,3]
输出:[1,3,2]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
示例 4:
输入:root = [1,2]
输出:[2,1]
示例 5:
输入:root = [1,null,2]
输出:[1,2]
思路一:递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void traveal(TreeNode* root,vector<int> &res){
if(root==nullptr) return;
traveal(root->left,res);
res.push_back(root->val);
traveal(root->right, res);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
traveal(root,res);
return res;
}
};
思路二:迭代
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
// vector<int> res; //用来返回值
// stack<TreeNode*> stk; //定义一个栈用来压入数据
// if(root==nullptr) return {}; //当为空时候返回
// while(root!=nullptr||!stk.empty()){
// while(root){
// stk.push(root); //根先入栈
// root = root->left; //访问左节点
// }
// root = stk.top(); //头取出
// stk.pop(); //头出栈
// res.push_back(root->val); //值取出
// root = root->right; //根节点
// }
vector<int> res; //定义返回的数组
stack<TreeNode*> stk; //定义进入栈的值
if(root==nullptr) return res; //返回数组
TreeNode* cur = root;
while(cur!=nullptr||!stk.empty()){
if(cur!=nullptr){
stk.push(cur);
cur = cur->left; //左边遍历
}else{ //当遍历到叶子节点之后
cur = stk.top(); //访问栈头
stk.pop(); //弹出栈头
res.push_back(cur->val); //结果压入栈
cur = cur->right; //取右节点
}
}
return res;
}
};