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 / \The above binary tree is serialized as
2 3
/ 4
\ 5
"{1,2,3,#,#,4,#,#,5}"
.
[Solution]
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
// result
vector<int> res;
// NULL node
if(root == NULL)return res;
// traversal the left brunch
if(root->left != NULL){
vector<int> left = inorderTraversal(root->left);
vector<int>::iterator leftIt;
for(leftIt = left.begin(); leftIt != left.end(); ++leftIt){
res.push_back(*leftIt);
}
}
// traversal the root
res.push_back(root->val);
// traversal the right brunch
if(root->right != NULL){
vector<int> right = inorderTraversal(root->right);
vector<int>::iterator rightIt;
for(rightIt = right.begin(); rightIt != right.end(); ++rightIt){
res.push_back(*rightIt);
}
}
return res;
}
};
说明:版权所有,转载请注明出处。 Coder007的博客