Skip to content

Commit 58be8dd

Browse files
committed
Day-61 One DP problem and finished chap 2 of CTCI2
1 parent e1c0b26 commit 58be8dd

File tree

4 files changed

+57
-7
lines changed

4 files changed

+57
-7
lines changed

tree_problems/.verticalSum.cpp.swp

12 KB
Binary file not shown.

tree_problems/run

21.6 KB
Binary file not shown.

tree_problems/sortedArrayToBST.cpp

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* Given a sorted array, convert it balaned binary search tree.
3+
*/
4+
5+
#include<iostream>
6+
#include<vector>
7+
8+
struct Node {
9+
int data;
10+
Node * left;
11+
Node * right;
12+
Node( int d ) : data{ d }, left{ nullptr }, right{ nullptr } { }
13+
};
14+
15+
Node * sortedArrayToBST( std::vector<int> & arr, int start, int end ) {
16+
if ( start > end ) {
17+
return nullptr;
18+
}
19+
int mid = ( start + end )/2;
20+
Node * node = new Node(arr[mid]);
21+
node->left = sortedArrayToBST( arr, start, mid - 1 );
22+
node->right = sortedArrayToBST( arr, mid + 1, end );
23+
return node;
24+
}
25+
26+
void printArray( std::vector<int> & arr ) {
27+
for ( auto i : arr ) {
28+
std::cout << i << " ";
29+
}
30+
std::cout << std::endl;
31+
}
32+
33+
void printTreeInOrder( Node * root ) {
34+
if( root ) {
35+
printTreeInOrder( root->left );
36+
std::cout << root->data << " ";
37+
printTreeInOrder( root->right );
38+
}
39+
}
40+
41+
int main() {
42+
std::vector<int> arr{ 1, 2, 3, 4, 5, 6, 7, 8 };
43+
std::cout << "Arr :";
44+
printArray(arr);
45+
Node * root = sortedArrayToBST(arr, 0, arr.size() - 1);
46+
std::cout << "Tree :";
47+
printTreeInOrder(root);
48+
std::cout << std::endl;
49+
return 0;
50+
}

tree_problems/sumTree.cpp

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@
44
* An empty tree is SumTree and sum of an empty tree can be considered as 0.
55
* A leaf node is also considered as SumTree.
66
*
7-
* 26
8-
* / \
7+
* 26
8+
* / \
99
* 10 3
10-
* / \ \
11-
* 4 6 3
10+
* / \ \
11+
* 4 6 3
1212
*/
1313
#include <iostream>
1414

@@ -63,10 +63,10 @@ void inorder(Node * root)
6363
int main()
6464
{
6565
/**
66-
* 26
67-
* / \
66+
* 26
67+
* / \
6868
* 10 3
69-
* / \ \
69+
* / \ \
7070
* 4 6 3
7171
*/
7272
Node * root = new Node(26);

0 commit comments

Comments
 (0)