二叉树中序遍历(迭代)

 

 

 

 

 class Solution {
  public:
      vector<int> inorderTraversal(TreeNode* root) {
          stack<TreeNode*> s;
          vector<int> v;
          TreeNode* now = root;
          while (now != NULL || !s.empty()) {
              //将当前节点和当前结点的左节点入栈
              while (now != NULL) {
                  s.push(now);
                  now = now->left;
              }
              //从最后一个左节点开始处理,依次将左节点、根节点、右节点的值加入数组
              now = s.top();
              s.pop();
              v.push_back(now->val);
              now = now->right;
          }
          return v;
      }
  };

 

posted @ 2020-05-15 15:44  知道了呀~  阅读(326)  评论(0编辑  收藏  举报