问题描述:
翻转一颗二叉树。
实现思路:
递归遍历,从二叉树的最下端(即叶子节点出)进行交换,依次往上进行交换。
实现代码:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
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) {
invertBinaryTree(root->left);
invertBinaryTree(root->right);
swap(root->left, root->right);
}
}
};
感想:
翻转二叉树要从下往上进行。利用递归,先将叶子节点进行翻转,然后依次往上进行。