0226.cpp (433B)
1 class Solution { 2 public: 3 TreeNode *invertTree(TreeNode *root) { 4 if (!root) return nullptr; 5 6 stack<TreeNode *> st; 7 st.push(root); 8 while (!st.empty()) { 9 TreeNode *root = st.top(); 10 st.pop(); 11 swap(root->left, root->right); 12 if (root->left) st.push(root->left); 13 if (root->right) st.push(root->right); 14 } 15 return root; 16 } 17 };