翻转二叉树

来源:互联网 发布:淘宝达人简介范文 编辑:程序博客网 时间:2024/06/05 11:42

一、问题描述

   翻转一棵二叉树

样例

  1         1 / \       / \2   3  => 3   2   /       \  4         4
二、解题思路

         运用递归算法,前序遍历此二叉树的左右子树,然后运用swap函数交换左右子树即可。

三、我的代码

class Solution {
public:
    /**
     * @param root: a TreeNode, the root of the binary tree
     * @return: nothing
     */
    void invertBinaryTree(TreeNode *root) {
        if(root==NULL)  return;
        swap(root->left,root->right);
        invertBinaryTree(root->left);
        invertBinaryTree(root->right);
    }
};

四、我的感想

       做这道题首先想到交换运用的swap函数,然后问题就简单化了,以前的知识到现在依然很有用,想到有必要去翻翻以前的课本了。

0 0
原创粉丝点击