给你二叉树的根节点 root ,返回它节点值的 中序 遍历。
学习点
- 迭代法需要特殊处理。需要额外定义一个指针指向正在处理的节点,否则在回溯节点的时候,会重复遍历之前访问过的节点。
代码
递归法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public: void inOrder(TreeNode *root, vector<int> &res) { if (root == nullptr) return; inOrder(root->left, res); res.push_back(root->val); inOrder(root->right, res); }
vector<int> inorderTraversal(TreeNode *root) { vector<int> res; inOrder(root, res); return res; } };
|
迭代法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| class Solution { public: void inOrder(TreeNode *root, vector<int> &res) { if (root == nullptr) return; inOrder(root->left, res); res.push_back(root->val); inOrder(root->right, res); }
vector<int> inorderTraversal(TreeNode *root) {
vector<int> res; stack<TreeNode*> st; TreeNode* curr = root; while (curr != nullptr || !st.empty()) { if (curr != nullptr) { st.push(curr); curr = curr->left; } else { curr = st.top(); st.pop(); res.push_back(curr->val); curr = curr->right; } }
return res; } };
|