Skip to content

Commit 89dd670

Browse files
committed
Added Leetcode Problem:226 codeharborhub#908
1 parent 561a17f commit 89dd670

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
---
2+
id: invert binary search tree
3+
title: Invert Binary Search Tree
4+
sidebar_label: 0226 Invert Binary Search Tree
5+
tags:
6+
- tree
7+
- recursion
8+
- LeetCode
9+
- C++
10+
description: "This is a solution to the Invert Binary Search Tree problem on LeetCode."
11+
---
12+
13+
## Problem Description
14+
15+
Given the root of a binary tree, invert the tree, and return its root.
16+
17+
### Examples
18+
19+
**Example 1:**
20+
21+
```
22+
23+
Input: root = [4,2,7,1,3,6,9]
24+
Output: [4,7,2,9,6,3,1]
25+
```
26+
27+
**Example 2:**
28+
29+
```
30+
Input: root = [2,1,3]
31+
Output: [2,3,1]
32+
```
33+
34+
```
35+
Input: root = []
36+
Output: []
37+
```
38+
39+
### Constraints
40+
41+
- The number of nodes in the tree is in the range $[0, 100]$.
42+
- `-100 <= Node.val <= 100`
43+
44+
### Approach
45+
46+
To solve this problem(invert BST) we will use recursion(call function repeatedly) and temporary tree node(t) for swapping.
47+
48+
#### Code in C++
49+
50+
```cpp
51+
/**
52+
* Definition for a binary tree node.
53+
* struct TreeNode {
54+
* int val;
55+
* TreeNode *left;
56+
* TreeNode *right;
57+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
58+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
59+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
60+
* };
61+
*/
62+
class Solution {
63+
public:
64+
void invert(TreeNode* root){
65+
if(root==NULL){
66+
return;
67+
}
68+
TreeNode* t;
69+
t=root->right;
70+
root->right=root->left;
71+
root->left=t;
72+
invert(root->left);
73+
invert(root->right);
74+
}
75+
TreeNode* invertTree(TreeNode* root) {
76+
invert(root);
77+
return root;
78+
79+
}
80+
};
81+
```
82+
83+

0 commit comments

Comments
 (0)