对代码思路的描述即:解释代码:
例:
取栈顶。
当栈顶不为空:入栈顶的左右中,入中后再入一个NULL。
再取栈顶(即中元素后一个元素(NULL))此时节点为空。当节点为空:去NULL,存中元素值,再去中元素。再取栈顶,此时栈顶为左孩子,然后将左孩子作为根重新操作。
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
stack<TreeNode*> st;
if (root != NULL) st.push(root);
while (!st.empty()) {
TreeNode* node = st.top();
if (node != NULL) {
st.pop();
if (node->right) st.push(node->right); // 右
if (node->left) st.push(node->left); // 左
st.push(node); // 中
st.push(NULL);
} else {
st.pop();
node = st.top();
st.pop();
swap(node->left, node->right); // 节点处理逻辑
}
}
return root;
}
};