ゼロから始まるLCブラシ問題(55):Invert Binary Treeツリー反転
原題:
Invert a binary tree.
Example:
Input:
Output:
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.
コード:
ループ反転も面倒ではありません.まず左右のサブツリーを反転してから、左右のサブツリーのルートノードをスタックに入ればいいです.結果:
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.
コード:
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;
}
};