94. Binary Tree Inorder Traversal

struct TreeNode{ int val; TreeNode * left; TreeNode * right; }; // 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

Note first: if you are writing this function yourself, can you figure out the return type?

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.