Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree [1,null,2,3],
1
\
2
/
3
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int>vec;
vector<int> inorderTraversal(TreeNode* root) {
if(root==NULL)return vec;
else{
if(root->left!=NULL&&root->right!=NULL){
inorderTraversal(root->left);
vec.push_back(root->val);
inorderTraversal(root->right);
}
else if(root->right!=NULL&&root->left==NULL){
vec.push_back(root->val);
inorderTraversal(root->right);
}
else if(root->right==NULL&&root->left!=NULL){
inorderTraversal(root->left);
vec.push_back(root->val);
}
else{
vec.push_back(root->val);
}
}
return vec;
}
};
不知道为啥这种题还是中等难度。