首先心疼 Max Howell 一秒钟。
首先,递归。
- return NULL , if root is NULL
- swap left and right
- recur left child and right child
TreeNode* invertTree(TreeNode* root)
{
if(root)
{
invertTree(root->left);
invertTree(root->right);
swap(root->left, root->right);
}
return root;
}
然后,用栈非递归。(用队列也是差不多的)
- stack save each node and swap their child if they have.
TreeNode* invertTree(TreeNode* root)
{
stack<TreeNode*> sta;
if(root)
sta.push(root);
while(!sta.empty())
{
TreeNode* t = sta.top();
sta.pop();
if(t->left)
sta.push(t->left);
if(t->right)
sta.push(t->right);
swap(t->left, t->right);
}
return root;
}
for ending ,i realize how swap function strong is.