[LeetCode] Invert Binary Tree - 二叉树翻转系列问题

目录:
1.Invert Binary Tree - 二叉树翻转 [递归]


题目概述:

Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9
to
     4
   /   \
  7     2
 / \   / \
9   6 3   1
Trivia: 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.


题目分析:

        题目背景是MaxHowell(他是苹果电脑最受欢迎的homebrew程序作者)去Google面试,面试官说:“虽然在Google有90%的工程师用你写的Homebrew,但是你居然不能再白板上写出翻转二叉树的代码,所以滚带吧”!
        该题最初想法就是通过递归依次交换左右结点,但是想得太多,如“是否需要再建一颗树”、“是否需要引入队列或BFS”,最终没有AC。


我的代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 //思路:二叉树递归 左右结点交换 在递归翻转左右子树
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        TreeNode *left, *right;
        if(root==NULL)
            return root;
        left = root->left;
        right = root->right;
        root->left = invertTree(right);
        root->right = invertTree(left);
        return root;
    }
};


其他代码:

        推荐阅读和采用二叉树非递归层次遍历算法实现如下。
        你会翻转二叉树吗?--谈程序员的招聘
        http://blog.csdn.net/sunao2002002/article/details/46482559

//第二种方法 通过队列层次遍历队列实现
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        queue<TreeNode*> q;
        if(root==NULL)
            return root;
        q.push(root);
        int size=q.size();
        while(size>0)
        {
            TreeNode *p=q.front();
            q.pop();
            //交换左右结点
            TreeNode *LNode=p->left;
            TreeNode *RNode=p->right;
            p->left=RNode;
            p->right=LNode;
            //进入队列
            if(p->left) {
                q.push(p->left);
            }
            if(p->right) {
                q.push(p->right);
            }
            size=q.size();
        }
        return root;
    }
};


其他题目:

(By:Eastmount 2015-9-12 凌晨5点半   http://blog.csdn.net/eastmount/)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Eastmount

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值