题目:Invert Binary Tree
要求:翻转一棵二叉树
样例:
1 1
/ \ / \
2 3 => 3 2
/ \
4 4
挑战:递归固然可行,能否写个非递归的?
难道:容易
递归版本:
class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
void swap(TreeNode* &a , TreeNode* &b)
{
TreeNode* tmp;
tmp = a;
a = b;
b = tmp;
}
void invertBinaryTree(TreeNode *root)
{
if (root != NULL)
{
swap(root->left,root->right);
invertBinaryTree(root->left);
invertBinaryTree(root->right);
}
}
};
迭代版本:
class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
void swap(TreeNode* &a , TreeNode* &b)
{
TreeNode* tmp;
tmp = a;
a = b;
b = tmp;
}
void invertBinaryTree(TreeNode *root)
{
if (root==NULL)
return;
std::stack<TreeNode*> S;
TreeNode *p = root;
while(p!=NULL)
{
swap(p->left,p->right);
if (p->right != NULL)
S.push(p->right);
if (p->left != NULL)
p = p->left;
else
{
if (S.empty())
break;
p = S.top();
S.pop();
}
}
}
};