以下代码实现了二叉树的中序遍历。输入以下二叉树,中序遍历结果是4 2 5 1 3 6。
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
void inorderIterative(TreeNode* root) {
stack<TreeNode*> st;
TreeNode* curr = root;
while (curr || !st.empty()) {
while (curr) {
st.push(curr);
curr = curr->left;
}
curr = st.top(); st.pop();
cout << curr->val << " ";
curr = curr->right;
}
}
正确
错误