思路 用一个stack<TreeNode *>解决问题。先尽可能往左地把节点放入栈。 每次取出节点并访问,再对它的右节点尽可能往左地放入栈即可。 详情
代码语言:javascript复制/**
* 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) {
stack<TreeNode *> st;
vector<int> res;
TreeNode *n = root;
while (n) {
st.push(n);
n = n->left;
}
while (!st.empty()) {
TreeNode *cur = st.top();
st.pop();
res.push_back(cur->val);
TreeNode *r = cur->right;
while(r) {
st.push(r);
r = r->left;
}
}
return res;
}
};