翻转一棵二叉树。
递归思想
从根节点起,一次翻转左右孩子的值,然后再对左右字数进行递归
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (nullptr == root || (root->right == nullptr && root->left == nullptr))
{
return root;
}
if (root->left == nullptr)
{
swap(root->left, root->right);
invertTree(root->left);
}
else if (root->right == nullptr)
{
swap(root->right, root->left);
invertTree(root->right);
}
else
{
swap(root->right, root->left);
invertTree(root->right);
invertTree(root->left);
}
return root;
}
};
非递归思想:
考虑采用层次遍历