Iteraviely:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
stack<TreeNode*> s;
vector<int> res;
if (!root) return res;
TreeNode *cur=root;
while (cur || s.size()) {
while (cur) {
s.push(cur);
cur = cur->left;
}
cur = s.top();
s.pop();
res.push_back(cur->val);
cur=cur->right;
}
return res;
}
};
DFS:
class Solution {
public:
void inorder(TreeNode *root, vector<int> &res) {
if (!root) return;
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right, res);
}
vector<int> inorderTraversal(TreeNode *root) {
vector<int> res;
inorder(root, res);
return res;
}
};
c++ header files http://en.cppreference.com/w/cpp/header