递归遍历
结点定义
class TreeNode{
int val;
TreeNode* left;
TreeNode* right;
};
void inorderTraverse(TreeNode* root){
if (root == nullptr) return;
inorderTraverse(root->left);
/*
需要执行的操作,比如下方的输出结点值
*/
cout << root->val << endl;
inorderTraverse(root->right);
}
非递归遍历
方法一:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> vi;
if (root == nullptr) return vi;
while (!st.empty() || root) {
while (root != nullptr) {
st.push(root);
root = root->left;
}
root = st.top();
st.pop();
vi.push_back(root->val);
root = root->right;
}
return vi;
}
方法二:
vector<int> inorderTraverse(TreeNode* root){
stack<TreeNode*> st;
vector<int> vi;
while (!st.empty() || root){
if (root){
st.push(root);
root = root->left;
} else {
root = st.top();
st.pop();
vi.push_back(root->val);
root = root->right;
}
}
return vi;
}
方法三:Morris 中序遍历
vector<int> inorderTraverse(TreeNode* root){
stack<int> st;
vector<int> vi;
TreeNode* predecessor = nullptr;
while (!st.empty() && root != nullptr){
// 如果左子树不为空,寻找其中序遍历的前驱结点
if (root->left != nullptr){
predecessor = root->left;
// 右子树不为空或还没处理
while (predecessor->right != nullptr && predecessor->right != root){
predecessor = predecessor->right;
}
// 找到了前驱结点,将其右子树指向当前结点
if (predecessor->right == nullptr){
predecessor->right = root;
root = root->left;
} else { // 左子树已遍历完
vi.push_back(root->val);
predecessor->right = nullptr;
root = root->right;
}
} else { // 左子树为空,直接访问当前结点,并指向右子树
vi.push_back(root->val);
root = root->right;
}
}
}