1. 题意
求二叉树中序遍历
2. 题解
2.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> ans;
vector<int> inorderTraversal(TreeNode* root) {
if(root == NULL) return ans;
if(root->left) ans = inorderTraversal(root->left);
ans.push_back(root->val);
if(root->right) ans = inorderTraversal(root->right);
return ans;
}
};
2.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:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
stack<TreeNode *> s;
while (!s.empty() || root ) {
if (root) {
s.push(root);
root = root->left;
continue;
}
root = s.top();
ans.emplace_back(root->val);
s.pop();
root = root->right;
}
return ans;
}
};