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]
.
Recursion
class Solution {
private:
vector<int> result;
public:
vector<int> inorderTraversal(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
result.clear();
if(!root) return result;
inorderTrav(root);
return result;
}
void inorderTrav(TreeNode *root)
{
if(root->left) inorderTrav(root->left);
result.push_back(root->val);
if(root->right) inorderTrav(root->right);
}
};
Iteration
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> result;
if(!root) return result;
stack<TreeNode*> stk;
TreeNode* p = root;
do
{
if(p!=NULL)
{
stk.push(p);
p=p->left;
}
else
{
p=stk.top();
result.push_back(p->val);
stk.pop();
p=p->right;
}
}while(!stk.empty()||p!=NULL); //注意判断条件
return result;
}
};