leetcode-94-树题-二叉树的中序遍历 发表于 2020-03-22 | 分类于 数据结构与算法 题目 解法1234567891011121314151617181920212223242526272829303132333435363738394041/** * 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) { vector<int> res; inorderTraversalCore(root, res); return res; } // 迭代 void inorderTraversalCore(TreeNode *root, vector<int> &res){ stack<TreeNode *> store; TreeNode *curr = root; while(curr || !store.empty()){ while(curr){ store.push(curr); curr = curr->left; } curr = store.top(); store.pop(); res.push_back(curr->val); curr = curr->right; } } 递归 void inorderTraversalCore(TreeNode *root, vector<int> &res){ if(!root) return; inorderTraversalCore(root->left, res); res.push_back(root->val); inorderTraversalCore(root->right, res); }};