地址:https://leetcode.com/problems/binary-tree-inorder-traversal/
题目:
Given a binary tree, return the inorder traversal of its nodes’ values.
Example:
理解:
二叉树的中序遍历
递归实现:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
InOrder(root, res);
return res;
}
void InOrder(TreeNode* root, vector<int>& res) {
if (!root) return;
InOrder(root->left, res);
res.push_back(root->val);
InOrder(root->right, res);
}
};
非递归实现:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> stk;
TreeNode* p = root;
while (p || !stk.empty()) {
if (p) {
stk.push(p);
p = p->left;
}
else {
p= stk.top();
stk.pop();
res.push_back(p->val);
p = p->right;
}
}
return res;
}
};
基于线索树的实现
前面两种空间复杂度都是
O
(
n
)
O(n)
O(n)
基于线索数,可以把空间复杂度变为
O
(
1
)
O(1)
O(1)
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
TreeNode* curr = root;
while (curr) {
if (curr->left) {
TreeNode* pre = curr->left;
while (pre->right && (pre->right != curr)) {
pre = pre->right;
}
//如果是第一次到达,修改线索树
if (!pre->right) {
pre->right = curr;
curr = curr->left;
}
//第二次到达,改回去
else {
pre->right = nullptr;
res.push_back(curr->val);
curr = curr->right;
}
}
else {
res.push_back(curr->val);
curr = curr->right;
}
}
return res;
}
};