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?
中序遍历,左->根->右的顺序,用栈来模拟递归思路。/**
* 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)
{
vector<int> values;
stack<TreeNode *> stk;
TreeNode *p = root;
while(p || !stk.empty())
{
while(p)
{
stk.push(p);
p = p->left;
}
if(!stk.empty())
{
p = stk.top();
stk.pop();
values.push_back(p->val);
p = p->right;
}
}
return values;
}
};
void inOrder1(BinTree *root) //递归中序遍历
{
if(root!=NULL)
{
inOrder1(root->lchild);
cout<<root->data<<" ";
inOrder1(root->rchild);
}
}