题目描述
给定一个二叉树的根节点 root
,返回 它的 中序 遍历 。
示例1.
输入:root = [1,null,2,3] 输出:[1,3,2]
示例2.
输入:root = [] 输出:[]
示例3.
输入:root = [1] 输出:[1]
解题思路:
方法1. 递归
题目要求的是中序遍历,那就按照 左-打印-右这种顺序遍历树就可以
终止条件:当前节点为空时
函数内:递归的调用左节点,打印当前节点,再递归调用右节点
/**
* 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>newRes;
traverse(root, newRes);
return newRes;
}
void traverse(TreeNode* root, vector<int>& res){
if(root==nullptr){
return;
}
traverse(root->left, res);
res.push_back(root->val);
traverse(root->right, res);
}
};
方法2. 迭代
递归的调用过程是不断往左边走,当左边走不下去了,就打印节点,并转向右边,然后右边继续这个过程。我们在迭代实现时,就可以用栈来模拟上面的调用过程。
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*>calc;
vector<int>res;
while(!calc.empty() || root!=nullptr){
if(root!=nullptr){
calc.push(root);
root=root->left;
}
else{
TreeNode* cur = calc.top();
res.push_back(calc.top()->val);
calc.pop();
root=cur->right;
}
}
return res;
}
};
迭代步骤如上。