翻转二叉树

来源:互联网 发布:呼市吉林大学网络教育 编辑:程序博客网 时间:2024/06/05 15:06

翻转二叉树

题目描述:

翻转一棵二叉树。
样例
  1         1 / \       / \2   3  => 3   2   /       \  4         4

解题思路:

利用递归算法,交换左子树和右子树。

实现代码:

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;
        swap(root->left,root->right);
        invertBinaryTree(root->left);
        invertBinaryTree(root->right);
    }
};

A题感悟:

大一学的STL现在几乎忘得差不多了,一开始根本没想到swap()这个函数,我是用了三四行代码把左子树和右子树的交换了的,可是提交之后数据不完全对,一直改不过来,就问了一下大神,才知道用这个函数如此简单。
0 0
原创粉丝点击