翻转二叉树
Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9
to
4 / \ 7 2 / \ / \ 9 6 3 1
思路:采取先序遍历,根>左子树>右子树,自上而下分别把结点的左子树和右子树翻转,例如,结点4的左子树2和右子树7调换
4 / \ 7 2 / \ / \ 6 9 1 3
再依次调用invertTree函数传左子树和右子树进去。.....
代码如下:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * struct TreeNode *left; 6 * struct TreeNode *right; 7 * }; 8 */ 9 struct TreeNode* invertTree(struct TreeNode* root) { 10 if(root==NULL) return NULL;//若结点为空,则返回null; 11 struct TreeNode *temp; //定义一个指针交换 12 temp = root->left; //左子树传给temp以待交换 13 root->left = root->right; //右子树给左子树 14 root->right = temp; 15 invertTree(root->left); //递归调用invertTree函数 16 invertTree(root->right); 17 return root; //返回树; 18 }