【leetcode 94. 二叉树的中序遍历】解题报告
方法一:递归
vector<int> res; vector<int> inorderTraversal(TreeNode* root) { if (!root) return res; if (root->left) inorderTraversal(root->left); res.push_back(root->val); if (root->right) inorderTraversal(root->right); return res; }
方法二:非递归
vector<int> inorderTraversal(TreeNode* root) { vector<int> res; if (!root) return res; stack<TreeNode*> S; TreeNode* p = root; while(p||!S.empty()) { if (p) { S.push(p); p=p->left; } else { p=S.top(); S.pop(); res.push_back(p->val); p=p->right; } } return res; }