从零开始的LC刷题(55): Invert Binary Tree 二叉树翻转

原题:

Invert a binary tree.

Example:

Input:

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

Output:

     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 f*** off.

这道题很皮地把名句让大家茶余饭后笑笑,看到了大家都知道是什么事情了。

后序dfs,递归的解法很简单,不多赘述了,结果:

Success

Runtime: 0 ms, faster than 100.00% of C++ online submissions for Invert Binary Tree.

Memory Usage: 9.2 MB, less than 20.77% of C++ online submissions for Invert Binary Tree.

代码:

/**
 * 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) {
        if(root==nullptr){return root;}
        invertTree(root->left);
        invertTree(root->right);
        TreeNode *temp=root->right;
        root->right=root->left;
        root->left=temp;
        return root;
    }
};

循环翻转也不麻烦,先翻转左右子树然后左右子树根节点入栈就行,结果:

Success

Runtime: 0 ms, faster than 100.00% of C++ online submissions for Invert Binary Tree.

Memory Usage: 9.2 MB, less than 41.06% of C++ online submissions for Invert Binary Tree.

代码:

/**
 * 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) {
        vector lib;
        lib.push_back(root);
        while(!lib.empty()){
            TreeNode *r=lib.back();
            lib.pop_back();
            if(r==nullptr){continue;}
            TreeNode *temp=r->right;
            r->right=r->left;
            r->left=temp;
            lib.push_back(r->left);
            lib.push_back(r->right);
        }
        return root;
    }
};

 

你可能感兴趣的:(LEETCODE,C++)