struct TreeNode{
int val;
TreeNode * left;
TreeNode * right;
TreeNode (int x): val(x), left(NULL), right(NULL){}
};
// recursion
vector<int> inorderTraversal(TreeNode * root){
vector<int> v;
while(root != NULL){
v.push_back(root->val);
v.insert(v.end(); inorderTraversal(v->left).begin(); inorderTraversal(v->left).end());
v.insert(v.end(); inorderTraversal(v->right).begin(); inorderTraversal(v->right).end());
}
return v;
}
// correct solution
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> nodes;
inorder(root, nodes);
return nodes;
}
private:
void inorder(TreeNode* root, vector<int>& nodes) {
if (!root) {
return;
}
inorder(root -> left, nodes);
nodes.push_back(root -> val);
inorder(root -> right, nodes);
}
};
Given a binary tree, return the inorder traversal of its nodes' values.
1 Response
Write a comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.