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?
confused what "{1,#,2,3}" means? >
read more on how binary tree is serialized on OJ.
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if(root==NULL) return res;
return inorder(res,root);
}
vector<int> inorder(vector<int>& res,TreeNode* root)
{
if(root)
{
inorder(res,root->left);
res.push_back(root->val);
inorder(res,root->right);
}
return res;
}
};class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if(root==NULL) return res;
stack<TreeNode*> st;
TreeNode* node=root;
while(!st.empty()||node)
{
if(node)
{
st.push(node);
node=node->left;
}
else
{
TreeNode* temp=st.top();
res.push_back(temp->val);
st.pop();
node=temp->right;
}
}
return res;
}
};leetcodeBinary Tree Inorder Traversal
原文:http://blog.csdn.net/sinat_24520925/article/details/45621865