给定一个二叉树的根节点 root
,返回 它的 中序 遍历 。
示例 1:
输入:root = [1,null,2,3] 输出:[1,3,2]
示例 2:
输入:root = [] 输出:[]
示例 3:
输入:root = [1] 输出:[1]
提示:
- 树中节点数目在范围
[0, 100]
内 -100 <= Node.val <= 100
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
代码:
/**
* 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;
TreeNode *pre = nullptr;
while (root != nullptr) {
if (root->left != nullptr) {
pre = root->left;
while (pre->right != nullptr && pre->right != root) {
pre = pre->right;
}
if (pre->right == nullptr) {
pre->right = root;
root = root->left;
}
else {
res.push_back(root->val);
pre->right = nullptr;
root = root->right;
}
}
else {
res.push_back(root->val);
root = root->right;
}
}
return res;
}
};