leetcode(리트코드)226-Invert Binary Tree
leetcode(리트코드)226-Invert Binary Tree
leetcode 226 - Invert Binary Tree 문제입니다.
1. 문제
https://leetcode.com/problems/invert-binary-tree/
2. Input , Output
Constraints:
- The number of nodes in the tree is in the range [0, 100].
- -100 <= Node.val <= 100
3. 분류 및 난이도
Eazy 난이도 문제입니다.
leetcode Top 100 Liked 문제입니다.
4. 문제 해석
- 주어진 트리를 대칭으로 바꿔버립니다.
5. code
c++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root!=nullptr)
{
invertTree(root->left);
invertTree(root->right);
std::swap(root->left,root->right);
}
return root;
}
};
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if root :
self.invertTree(root.left)
self.invertTree(root.right)
root.left,root.right = root.right,root.left
return root
6. 결과 및 후기, 개선점
코드에 대한 설명이 필요하신 분은 댓글을 달아주세요.!!
결과는 4ms라 0ms랑 차이가 없으므로 개선사항은 없습니다.
This post is licensed under CC BY 4.0 by the author.