翻转一棵二叉树。
示例:
输入:
4
/
2 7
/ \ /
1 3 6 9
输出:
4
/
7 2
/ \ /
9 6 3 1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/invert-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
//思路:采取递归实现,判断每一个节点,反转他的子节点,然后递归翻转该结点的子节点的子节点
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
typedef struct TreeNode Node;
struct TreeNode* invertTree(struct TreeNode* root) {
Node *tempNode = NULL;
if(root == NULL )
{
return NULL;
}
if(root->left == NULL && root->right == NULL )
{
return root;
}
else if(root->left == NULL )
{
root->left = root->right;
root->right = NULL;
}
else if(root->right == NULL )
{
root->right = root->left;
root->left = NULL;
}
else
{
tempNode = root->left;
root->left = root->right;
root->right = tempNode;
}
invertTree(root->left);
invertTree(root->right);
return root;
}