中序遍历的方法

1:递归法

vector<int> result;
getValue(TreeNode* root, vector<int>& result) {
  if (root != nullptr) {
    getValue(root->left, result);
    result.emplace_back(root->val);
    getValue(root->right, result);
}

2. 迭代法

while (!stack.empty() || root != nullptr) {
  // 1. 一直遍历左子树   
while (root != nullptr) {     stack.push(root);     root = root -> left;   }

  // 2. 直到无法遍历,从stack取出一个值,把value放入vector   root
= stack.top();   stack.pop();
  result.emplace_back(root->val);

  // 3. 检查右子树,若右子树有值,则以右子树为root进行遍历(步骤1)
  // 若右子树为空,则继续从stack取值(步骤2)
  root
= root -> right; }

理解并熟练掌握迭代法!

原文地址:https://www.cnblogs.com/Younger-Zhang/p/15256239.html