Problem: 94. 二叉树的中序遍历
思路
利用线索树的思维,用空闲的右指针保存访问顺序,使得空间复杂度为O(1)。
要记得及时还原指针,毕竟是外部的数据。
复杂度
- 时间复杂度: $O(n)$
- 空间复杂度: $O(1)$
Code
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
| class Solution { public: vector<int> inorderTraversal(TreeNode *root) { vector<int> res; TreeNode *node = root; TreeNode *predecessor = nullptr; while (node != nullptr) { if (node->left != nullptr) { predecessor = node->left; while (predecessor->right != nullptr && predecessor->right != node) { predecessor = predecessor->right; } if (predecessor->right != node) { predecessor->right = node; node = node->left; } else { predecessor->right = nullptr; res.push_back(node->val); node = node->right; } } else { res.push_back(node->val); node = node->right; } } return res; } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public: vector<int> inorderTraversal(TreeNode *root) { vector<int> res; TreeNode *node = root; inOrder(root, res); return res; } void inOrder(TreeNode *node, vector<int> &res) { if (node == nullptr) { return; } inOrder(node->left, res); res.push_back(node->val); inOrder(node->right, res); return; } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public: vector<int> inorderTraversal(TreeNode *root) { vector<int> res; stack<TreeNode *> treeStack; TreeNode *node = root; while (node != nullptr || !treeStack.empty()) { while (node != nullptr) { treeStack.push(node); node = node->left; } node = treeStack.top(); treeStack.pop(); res.emplace_back(node->val); node = node->right; } return res; } };
|