阅读下面用栈实现的非递归深度优先遍历代码:
void dfs(TreeNode* root) {
if (root == nullptr) return;
stack<TreeNode*> st;
st.push(root);
while (!st.empty()) {
TreeNode* node = st.top();
st.pop();
cout << node->val << " ";
if (node->right) st.push(node->right);
if (node->left) st.push(node->left);
}
}
对下面这棵树执行上述代码,输出是( )。
1
/ \
2 3
/ \ \
4 5 6
- A.
1 2 4 5 3 6 - B.
1 3 6 2 5 4 - C.
1 2 3 4 5 6 - D.
4 5 2 6 3 1