翻转二叉树

2015 年 6 月 10 日,Homebrew 的作者 @Max Howell 在 twitter 上发表了如下一内容:

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.

事情大概是说,Max Howell 去 Google 面试,面试官说:虽然在 Google 有 90% 的工程师用你写的 Homebrew,但是你居然不能在白板上写出翻转二叉树的代码,所以滚蛋吧。


翻转一棵二叉树

样例

  1         1
 / \       / \
2   3  => 3   2
   /       \
  4         4

/**

 * Definition for a binary tree node.

 * struct TreeNode {

 *    int val;

 *    struct TreeNode *left;

 *    struct TreeNode *right;

 * };

 */

struct TreeNode* invertTree(structTreeNode* root) {

   

}

 

递归版本

先翻转左子树,后翻转右子树,然后对整个树进行翻转

void swapTree(TreeNode *&root){
    TreeNode *tmp = root->left;
    root->left = root->right;
    root->right = tmp;
}

void invertBinaryTree(TreeNode *root) {
    // write your code here
    if(root == NULL)
        return;

    invertBinaryTree(root->left);
    invertBinaryTree(root->right);

    swapTree(root);
}

非递归版本

非递归版本用栈来实现,到访问到头节点的时候,将其左子树和右子树互换即可。

void swapTree(TreeNode *&root){
    TreeNode *tmp = root->left;
    root->left = root->right;
    root->right = tmp;
}
void invertBinaryTree(TreeNode *root) {
    // write your code here
    if(root == NULL)
        return;
    stack<TreeNode*> stk;
    stk.push(root);
    while(!stk.empty())
    {
        TreeNode *tmp = stk.top();
        stk.pop();
        swapTree(tmp);
        if(tmp->left)
            stk.push(tmp->left);
        if(tmp->right)
            stk.push(tmp->right);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值