Input: root = [1,null,2,3]
Output: [1,3,2]
Input: root = []
Output: []
Input: root = [1]
Output: [1]
Input: root = [1,2]
Output: [2,1]
Input: root = [1,null,2]
Output: [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:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> values;
inorderTraversal(root, values);
return values;
}
void inorderTraversal(TreeNode* root, vector<int> &values) {
if (root == nullptr) return;
inorderTraversal(root->left, values);
values.push_back(root->val);
inorderTraversal(root->right, values);
}
};
/**
* 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> values; stack<TreeNode*> nodes;
TreeNode* current = root;
while (!nodes.empty() || current != nullptr) {
if (current != nullptr) {
nodes.push(current);
current = current->left;
} else {
values.push_back(nodes.top()->val);
current = nodes.top()->right;
nodes.pop();
}
}
return values;
}
};