leetcodeノート:Invert Binary Tree
一.タイトルの説明
Invert a binary tree.
to
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.
二.テーマ分析
テーマの意図は明らかで、つまり二叉木を反転させる.后ろはいくつかの言叶で、大体の意味は:
Google:エンジニアの90%があなたが書いたソフトウェア(Homebrew?)を使っています.しかし、あなたは意外にも白い板の上で1本の二叉の木をひっくり返すことができなくて、本当に卵を操っています.
これは任意のプログラマーができるべき問題であり,再帰的またはキュー反復解法が実現でき,余計な説明はない.
三.サンプルコード
四.小結
この問題は、データ構造の基礎を復習するのに役立ちます.
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.
二.テーマ分析
テーマの意図は明らかで、つまり二叉木を反転させる.后ろはいくつかの言叶で、大体の意味は:
Google:エンジニアの90%があなたが書いたソフトウェア(Homebrew?)を使っています.しかし、あなたは意外にも白い板の上で1本の二叉の木をひっくり返すことができなくて、本当に卵を操っています.
これは任意のプログラマーができるべき問題であり,再帰的またはキュー反復解法が実現でき,余計な説明はない.
三.サンプルコード
// C++,
/** * 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 == NULL) return root;
TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
invertTree(root->left);
invertTree(root->right);
return root;
}
};
# Python,
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def invertTree(self, root):
""" :type root: TreeNode :rtype: TreeNode """
if root is None:
return None
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
四.小結
この問題は、データ構造の基礎を復習するのに役立ちます.