Given a binary tree, return the inorder traversal of its nodes’ values.
For example: Given binary tree {1,#,2,3}, 1
2 / 3 return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
confused what “{1,#,2,3}” means? > read more on how binary tree is serialized on OJ.
实现:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> val;
vector<TreeNode*> record;
vector<TreeNode*> traverse;
if (root == NULL) return val;
record.push_back(root);
while (record.size() > 0)
{
TreeNode *node = record.back();
if ((node->left && std::find(traverse.begin(), traverse.end(), node->left) != traverse.end()) || node->left == NULL) {
val.push_back(node->val);
record.pop_back();
traverse.push_back(node);
if (node->right) {
record.push_back(node->right);
}
}
else if (node->left)
{
record.push_back(node->left);
continue;
}
}
return val;
}
};