问题描述:
翻转一棵二叉树
样例
解题思路:
1 1
/ \ / \
2 3 => 3 2
/ \
4 4
判断根节点是否为空,若根节点是否为空,则返回为空;将左子树赋给node,然后分别遍历左子树和右子树,遍历右子树将值赋给左子树,再将左子树赋给右子树,返回这棵树,实现二叉树的翻转。
代码实现:
class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
void invertBinaryTree(TreeNode *root) {
// write your code here
if(root==NULL)
return NULL;
node=invertBinaryTree(root->left);
root->left=invertBinaryTree(root->right);
root->right=node;
return tree;
}
};
感想:
将左子树和右子树按照前序遍历的顺序进行遍历,然后将左右子树进行交换,实现二叉树的翻转。