题目:
给定一个二叉树的根节点root,返回中序遍历
代码:
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
//定义二叉树节点
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> vals;
vector<int> inorderTraversal(TreeNode* root) {
scan(root);
return vals;
}
void scan(TreeNode* root){
if(!root){
return ;
}
inorderTraversal(root->left);
vals.push_back(root->val);
inorderTraversal(root->right);
}
};
//迭代法
class anotherSolution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
//开一个栈的原因:记录每个节点出栈顺序,遍历对应的值
stack<TreeNode*> s;
//如果root不空或者栈也不空就继续
while(root != nullptr || !s.empty()){
//迭代的思想:从根节点走完左子树,再根据中序遍历先左后根再右
while(root != nullptr){//要把当前root节点作为判断条件,而不是root->left
s.push(root);
root = root->left;
}
TreeNode* getVal = s.top();
res.push_back(getVal->val);
s.pop();
root = getVal->right;
}
return res;
}
};
int main(){
return 0;
}