반응형
https://leetcode.com/problems/invert-binary-tree/description/
Invert Binary Tree - LeetCode
Can you solve this real interview question? Invert Binary Tree - Given the root of a binary tree, invert the tree, and return its root. Example 1: [https://assets.leetcode.com/uploads/2021/03/14/invert1-tree.jpg] Input: root = [4,2,7,1,3,6,9] Output: [4
leetcode.com
트리를 후위 순회하면서, 방문했던 좌측 노드와 우측 노드를 스왑해주었습니다.
전위 순회하여도 동일한 결과를 얻을 수 있습니다.
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root) return NULL;
invertTree(root->left);
invertTree(root->right);
swap(root->left, root->right);
return root;
}
private:
void swap(TreeNode*& a, TreeNode*& b) {
TreeNode* temp = a;
a = b;
b = temp;
}
};
반응형
'Algorithm' 카테고리의 다른 글
LeetCode 35 - Search Insert Position (0) | 2023.02.20 |
---|---|
LeetCode 103 - Binary Tree Zigzag Level Order Traversal (0) | 2023.02.19 |
LeetCode 783 - Minimum Distance Between BST Nodes (1) | 2023.02.18 |
LeetCode 104 - Maximum Depth of Binary Tree (0) | 2023.02.16 |
LeetCode 989 - Add to Array-Form of Integer (0) | 2023.02.15 |