[Problem]
[Solution]
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?
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
.
[Solution]
/**说明:版权所有,转载请注明出处。 Coder007的博客
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> res;
if(root == NULL){
return res;
}
// visit the left brunch
vector<int> left = inorderTraversal(root->left);
// visit the right brunch
vector<int> right = inorderTraversal(root->right);
// add result
for(int i = 0; i < left.size(); ++i){
res.push_back(left[i]);
}
res.push_back(root->val);
for(int i = 0; i < right.size(); ++i){
res.push_back(right[i]);
}
return res;
}
};