LeetCode #226 - Invert Binary Tree - Easy

来源:互联网 发布:网络金融的发展趋势 编辑:程序博客网 时间:2024/04/26 13:45

Problem

Invert a binary tree.

Example

     4   /   \  2     7 / \   / \1   3 6   9->     4   /   \  7     2 / \   / \9   6 3   1

Algorithm

整理一下题意:翻转一棵二叉树。

首先想到的当然是递归解法。对每个节点,都翻转左右子树。

代码如下。

//递归版本,用时0msclass Solution {public:    TreeNode* invertTree(TreeNode* root) {        if(root==NULL) return NULL;        TreeNode* temp=root->left;        root->left=invertTree(root->right);        root->right=invertTree(temp);        return root;    }};

然而,
题目中写了这么一句

This problem was inspired by this original tweet by Max Howell:Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

那么这题真有这么简单?刚刚的递归解法AC了,那么尝试一下非递归解法吧。

要翻转整棵树,那么对每个左子和右子都要翻转。由于左子和右子交换时,左子和右子的子树也随之交换,所以只要对左子右子做处理即可。交换的左子和右子必然是在同一层的,那么可以考虑通过层次遍历来实现。
在层次遍历的过程中,对每个左子和右子都进行交换。对子树为NULL的情况稍作处理即可。

代码如下。

//非递归版本,用时3msclass Solution {public:    TreeNode* invertTree(TreeNode* root) {        if(root==NULL) return NULL;        queue<TreeNode*> q;        TreeNode* p;        TreeNode* temp;        q.push(root);        while(!q.empty()){            p=q.front();            q.pop();            temp=p->left;            p->left=p->right;            p->right=temp;            if(p->left!=NULL) q.push(p->left);            if(p->right!=NULL) q.push(p->right);        }        return root;    }};

提交代码,AC。没想到用时反而比递归版本还长。所以Max Howell那句话真是在开玩笑嘛…

0 0
原创粉丝点击