题意:非递归实现二叉树的中序遍历。
/** * 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> inorderTraversal(TreeNode* root) { vector<int> ans; if(root == NULL) return ans; stack<TreeNode*> s; TreeNode* pos = root; while(pos != NULL || !s.empty()){ while(pos){ s.push(pos); pos = pos -> left; } TreeNode* cur = s.top(); s.pop(); ans.push_back(cur -> val); pos = cur -> right; } return ans; } };