整体的思路就是:

    • 将整棵树的最左边一条链压入栈中
    • 每次取出栈顶元素,如果有右子树,则将右子树压入栈中
      1. /**
      2. * Definition for a binary tree node.
      3. * struct TreeNode {
      4. * int val;
      5. * TreeNode *left;
      6. * TreeNode *right;
      7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
      8. * };
      9. */
      10. class Solution {
      11. public:
      12. vector<int> inorderTraversal(TreeNode* root) {
      13. stack<TreeNode*> st;
      14. vector<int> res;
      15. TreeNode *p = root;
      16. while(p||st.size()){
      17. while(p){
      18. st.push(p);
      19. p = p->left;
      20. }
      21. p = st.top(); st.pop();
      22. res.push_back(p->val);
      23. p = p->right;
      24. }
      25. return res;
      26. }
      27. };