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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> result(0);
if (root == NULL)
return result;
stack<TreeNode*> stk;
TreeNode* p = root;
do
{
if (p != NULL)
{
stk.push(p);
p = p->left;
}
else
{
p = stk.top();
stk.pop();
result.push_back(p->val);
p = p->right;
}
}while(!stk.empty() || p != NULL);
return result;
}
};